Linux线程共享内存空间是指多个线程可以访问同一个内存区域,这些线程共享该内存区域的内容。
代码:
#include <stdio.h>
#include <pthread.h>
// share memory
int data = 0; //定义一个全局变量data
void *fun1(void *arg)
{
printf("t1:thread id is:%ld\n",(unsigned long)pthread_self());
printf("t1:is param:%d\n",*((int *)arg));
while(1){
printf("线程t1拿到 data = %d\n",data++);
sleep(1);
}
}
void *fun2(void *arg)
{
printf("t2:thread id is:%ld\n",(unsigned long)pthread_self());
printf("t2:is param:%d\n",*((int *)arg));
while(1){
printf("线程t2拿到 data = %d\n",data++);
sleep(1);
}
}
int main()
{
int ret;
pthread_t t1;
pthread_t t2;
int param = 100;
if(ret = pthread_create(&t1,NULL,fun1,(void *)¶m) == 0){
printf("main:creat t1 pthread successfully !\n");
}
if(ret = pthread_create(&t2,NULL,fun2,(void *)¶m) == 0){
printf("main:creat t2 pthread successfully !\n");
}
printf("main:获取主程序的ID:%ld\n",(unsigned long)pthread_self());
while(1){
printf("主进程main拿到 data = %d\n",data++);
sleep(1);
}
pthread_join(t1,NULL);
pthread_join(t2,NULL);
return 0;
}
结果:
对全局变量进行操作,共享内存空间