线程默认共享数据段、代码段等地址空间,常用的是全局变量。而进程不共享全局变量,只能借助mmap。
//代码示例
#include <string.h>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int var = 100;
void *tfn(void *arg)
{
var = 200;
printf("In thread, the var is %d.\n",var);
return NULL;
}
int main(void)
{
pthread_t tid;
int ret;
printf("In main, the var is %d at first.\n",var);
ret = pthread_create(&tid, NULL, tfn, NULL);
if( ret != 0 ) //出错判断
{
fprintf(stderr,"pthread_create error: %s\n",strerror(ret));
exit(1);
}
sleep(1);
printf("In main, the var is %d after thread's ending.\n",var);
return 0;
}
[root@localhost 01_pthread_test]# ./pthrd_crt
In main, the var is 100 at first.
In thread, the var is 200.
In main, the var is 200 after thread's ending.
1万+

被折叠的 条评论
为什么被折叠?



