#include <pthread.h>
#include <stdio.h>
void* printHello (void* threadId)
{
pthread_t *my_tid = (pthread_t *)threadId;
printf ("\nIn `printHello ()`: thread id %ld", (long)*my_tid);
pthread_exit (NULL);
}
int main ()
{
pthread_t arrayOfThreadId [5];
int returnValue;
unsigned int iterate;
for (iterate = 0; iterate < 5; iterate++)
{
if (returnValue = pthread_create (&arrayOfThreadId [iterate],
NULL,
printHello,
(void*) &arrayOfThreadId [iterate]) != 0)
{
printf ("\nerror: pthread_create failed with error number %d", returnValue);
}
else
{
printf ("\nIn `main()`: creating thread %ld", arrayOfThreadId [iterate]);
}
}
printf ("\nBefore `return 0;` in `main()`");
pthread_exit (NULL);
return 0;
}
输出:
In
`main()`: creating thread 139683073914640
In `main()`: creating thread 139683065521936
In `main()`: creating thread 139683057129232
In `main()`: creating thread 139683048736528
In `main()`: creating thread 139683040343824
Before `return 0;` in `main()`
In `printHello ()`: thread id 140735115959408
In `printHello ()`: thread id 4195680
In `printHello ()`: thread id 0
In `printHello ()`: thread id 0
In `printHello ()`: thread id 139683073914640
为什么threadID不同?
我在这里错过了一些观点。我似乎意外地做错了。
答案 0 :(得分:4)
您正在传递threadId的地址,但是您将该地址转换为pthread_t,因此将arrayOfThreadId中元素的地址视为pthread_t。
请改为:
void* printHello (void* threadId)
{
pthread_t *my_tid = threadId;
printf ("\nIn `printHello ()`: thread id %ld\n", (long)*my_tid);
确保你的main()在所有线程完成之前不会退出,否则你可能会在线程进入之前销毁数组。