如果您将地址传递i
给调用中的每个线程pthread_create()
,那么您无法保证每个线程将在变量中看到什么值。线程 0 可能会看到诸如 2 或 3 之类的值,因为即使调用i
0 时为 0,但当pthread_create()
线程运行并读取变量时,主线程已经更改了该值。
例如,使用这个经过轻微修改的代码版本,我得到的输出是:
Hello world from thread 3
Hello world from thread 4
Hello world from thread 4
Hello world from thread 3
Hello world from thread 5
Hello world from thread 5
Hello world from thread 5
...
Hello world from thread 5
Hello world from thread 5
Hello world from thread 5
Main over and out
修改后的代码:
删除<math.h>
and 重复<stdio.h>
and <pthread.h>
; 删除了thread_no
变量;修复了线程函数的类型以匹配pthread_create()
预期等。
#include <pthread.h>
#include <stdio.h>
#define NO_OF_THREADS 5
void *print_function(void *ip);
void *print_function(void *ip)
{
int *i = ip;
int count;
for(count=0; count<10; count++)
printf("Hello world from thread %d\n",*i);
pthread_exit(NULL);
return 0;
}
int main(void)
{
pthread_t printThreads[NO_OF_THREADS];
int i;
for(i=0; i<NO_OF_THREADS; i++)
{
pthread_create(&printThreads[i], NULL, print_function,&i);
}
int j;
for(j=0;j<NO_OF_THREADS;j++)
pthread_join(printThreads[j],NULL);
puts("Main over and out");
return 0;
}
当我将代码修改为 printpthread_self()
以及 时*i
,我得到了输出:
0x10800f000: Hello world from thread 1
0x10800f000: Hello world from thread 4
0x10800f000: Hello world from thread 5
0x10800f000: Hello world from thread 5
0x10800f000: Hello world from thread 5
0x10800f000: Hello world from thread 5
0x10800f000: Hello world from thread 5
0x10800f000: Hello world from thread 5
0x10800f000: Hello world from thread 5
0x10800f000: Hello world from thread 5
0x108092000: Hello world from thread 5
0x108115000: Hello world from thread 5
0x108198000: Hello world from thread 5
0x10821b000: Hello world from thread 5
其中四个线程只看到值 5;其中之一(可能是“线程 0”)也必须看到值 1 和 4。这种行为也是不确定的。这是另一次运行的开始:
0x10432b000: Hello world from thread 3
0x1043ae000: Hello world from thread 4
0x104431000: Hello world from thread 4
0x1044b4000: Hello world from thread 4
0x104537000: Hello world from thread 5
0x10432b000: Hello world from thread 5
0x1043ae000: Hello world from thread 5
在这两种情况下,其余条目都是 echoing 的各种线程5
。