这是我的第一个pthread程序,我不知道为什么printf语句在子线程中打印两次:
int x = 1;
void *func(void *p)
{
x = x + 1;
printf("tid %ld: x is %d\n", pthread_self(), x);
return NULL;
}
int main(void)
{
pthread_t tid;
pthread_create(&tid, NULL, func, NULL);
printf("main thread: %ld\n", pthread_self());
func(NULL);
}
Run Code Online (Sandbox Code Playgroud)
在我的平台上观察到的输出(Linux 3.2.0-32-generic#51-Ubuntu SMP x86_64 GNU/Linux):
1.
main thread: 140144423188224
tid 140144423188224: x is 2
2.
main thread: 140144423188224
tid 140144423188224: x is 3
3.
main thread: 139716926285568
tid 139716926285568: x is 2
tid 139716918028032: x is 3
tid 139716918028032: x is …Run Code Online (Sandbox Code Playgroud) 我有一个小程序,我在OS课程的考试科目中找到.
void * func (void * p) {
int n = p;
printf("%d \n",n);
return NULL;
}
int main() {
int i;
pthread_t t[3];
for(i=0; i<3; i+=1)
pthread_create(&t[i] ,NULL, func, (void*)i);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我得到以下结果(每个数字后面有一个新行):
第1次运行:0 0
次运行:1 0 2 2
第3次运行:0 1 1
当我只创建3个线程时,为什么它会打印4位数.它怎么打印重复?
该代码在Ubuntu中使用gcc编译.
