编译pthreads程序时出现问题
我尝试用这个命令编译这个简单的 pthreads 程序
$ gcc -pthread -o pthreads pthreads.c
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
void *myThread(void *arg);
int main()
{
pthread_t mythread;
int ret;
ret = pthread_create( &mythread, NULL, myThread, NULL );
if (ret != 0){
printf( "Can't create pthread: %s", strerror(errno));
exit(-1);
}
return 0;
}
void *myThread(void *arg){
// Thread code goes here..
printf("OK! NOW ON THE THREAD\n");
pthread_exit(NULL);
}
但是当尝试 ./pthreads 时没有输出!
I tried to compile this simple pthreads program with this command
$ gcc -pthread -o pthreads pthreads.c
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
void *myThread(void *arg);
int main()
{
pthread_t mythread;
int ret;
ret = pthread_create( &mythread, NULL, myThread, NULL );
if (ret != 0){
printf( "Can't create pthread: %s", strerror(errno));
exit(-1);
}
return 0;
}
void *myThread(void *arg){
// Thread code goes here..
printf("OK! NOW ON THE THREAD\n");
pthread_exit(NULL);
}
but when trying ./pthreads there is no output presented!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要等待线程完成。否则,您可能会在线程开始执行之前退出。
You need to wait for the thread to finish. Otherwise you risk exiting before the thread starts executing.
您没有等待线程完成。您需要使用 pthread_join()。
You didn't wait for your thread to finish. You need to use pthread_join().
您的问题来自这样一个事实:您的主线程正在从 main 返回,因此调用 exit (或 _exit)。当程序退出时,所有正在运行的线程都会被杀死。在这种情况下,工作线程在被杀死之前没有时间执行。
您可以使用
pthread_join
等待线程完成,然后再从 main 返回。You problem comes from the fact that you're main thread is returning from main, and thus calling exit (or _exit). All running thread are killed when the program exit. In this case, the worker thread didn't have the time to execute before it is killed.
You can use
pthread_join
to wait for the completion of the thread before returning from main.Sanjit 的答案当然是正确的,但为了扩大您的线程工具箱,您还可以查看
pthread_barrier_wait
。当您有一个包含大量线程的简单程序并且 main 看起来像“启动所有工作线程并等待它们完成”时,让 main 和所有工作线程简单地等待屏障可能是一个不错的选择避免存储所有工作线程 ID 并将它们加入 for 循环的方法。屏障还有许多其他巧妙的用途,有时可以让您避免因使用互斥体和条件变量执行相同操作而带来不必要的复杂性。Sanjit's answer is certainly correct, but for the sake of enlarging your threads toolbox, you might also look at
pthread_barrier_wait
. When you have a simple program with a lot of threads andmain
looks like "start all worker threads and wait for them to finish", having main and all the workers simply wait on a barrier can be a nice way to avoid having to store all the worker thread ids and join them in a for loop. Barriers also have a lot of other neat uses that sometimes let you avoid unnecessary complexity from doing the same things with mutexes and condition variables.