我尝试创建3个线程来做事并重复2次,我预计所有线程都将使用pthread_exit(NULL)
退出,但似乎输出只显示一次,也许是线程只创造了一次......?
我对pthread_exit()
的使用感到困惑。
我可以通过使用这个来破坏线程是正确的吗?
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sched.h>
#define gettid() syscall(__NR_gettid)
void *f1(void *a)
{
printf("f1\n");
return NULL;
}
void *f2(void *a)
{
printf("f2\n");
return NULL;
}
int main(int argc, char const *argv[])
{
/* code */
pthread_t t0,t1,t2;
int i ;
for ( i = 0 ; i < 2 ; i++)
{
if (pthread_create(&t0,NULL,&f1,NULL)== -1)
printf("error 1\n");
if (pthread_create(&t1,NULL,&f2,NULL)== -1)
printf("error 2\n");
if (pthread_create(&t2,NULL,&f1,NULL)== -1)
printf("error 1\n");
pthread_join(t0,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_exit(NULL);
}
return 0;
}
答案 0 :(得分:1)
您可能不希望在调用它的地方调用pthread_exit(),因为这会导致主线程退出但允许其他线程继续运行。在这种情况下,您等待所有其他线程完成,然后退出主线程。因此,你的循环永远不会再次执行。
答案 1 :(得分:1)
输出只显示一次,也许线程只创建一次
代码在pthread_exit()
main()
for (i = 0 ; i < 2 ; i++)
{
...
pthread_exit(NULL);
}
所以由main()
表示的线程退出,不再进行进一步的迭代,所以每次调用pthread_create()
只进行一次。
要解决此问题,请在 pthread_exit()
循环之后调用for
:
for (i = 0 ; i < 2 ; i++)
{
...
}
pthread_exit(NULL);
我对pthread_exit()的使用感到困惑。
我可以通过使用这个来销毁线程是正确的吗?
pthread_exit()
结束调用主题。
分配给已结束线程的资源将被释放,具体取决于线程是分离还是附加,后者是默认值。
为状态中的线程释放线程的资源......
pthread_join()
pthread_join()
。要分离线程,请在要分离的线程的pthread-id上使用pthread_detach()
。
另请注意,对于最近的PThread-API实现,所有函数都会返回错误代码> 0
。
所以你应该改变
if (pthread_create(&t0, NULL,&f1, NULL)== -1)
printf("error 1\n");
是
if (0 != pthread_create(&t0, NULL,&f1, NULL))
{
printf("error 1\n");
}
甚至更好
int result;
...
if (0 != (result = pthread_create(&t0, NULL, &f1, NULL)))
{
errno = result;
perror("pthread_create() failed");
}
答案 2 :(得分:0)
在主要调用它的情况下,主线程将终止。
pthread_exit()
退出它调用的线程。您需要查看when-to-use-pthread-exit ?。