Pthread_t 没有开始
Pthread_t not starting
我写这个简短的例子是为了理解C.It中的线程编程应该写"thread 0"。但是没有输出。
这是代码。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int i=0;
pthread_mutex_t mutex;
void * fonction(){
pthread_mutex_lock(&mutex);
printf("thread %d \n",i++);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main(){
pthread_t a;
pthread_mutex_init(&mutex,NULL);
pthread_create(&a,NULL,fonction,NULL);
return EXIT_SUCCESS;
}
有人可以帮助我吗?
Ps : 我用这个编译的
gcc -pthread test.c -o test
在pthread_create()
之后和return EXIT_SUCCESS;
之前插入pthread_join(a, NULL)
以确保子线程在main()
之前完成 returns.
pthread_join()
是一种方法,但不是 唯一的 解决方案。
如果您的主线程不(需要)存活更长时间(比它创建的线程),它可以简单地退出 pthread_exit(0)
。
当主线程使用 pthread_exit()
退出时,进程将保持活动状态,直到进程中的 last 线程退出。
这在主线程执行 initialization/setup 并启动多个线程时非常有用,然后就不再需要了。
否则,它将不得不等待 all 个线程完成(请记住,当 main() 退出时,整个进程退出 - 调用 pthread_exit()
将仅退出 main 线程,不是整个进程)。
我写这个简短的例子是为了理解C.It中的线程编程应该写"thread 0"。但是没有输出。 这是代码。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int i=0;
pthread_mutex_t mutex;
void * fonction(){
pthread_mutex_lock(&mutex);
printf("thread %d \n",i++);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main(){
pthread_t a;
pthread_mutex_init(&mutex,NULL);
pthread_create(&a,NULL,fonction,NULL);
return EXIT_SUCCESS;
}
有人可以帮助我吗? Ps : 我用这个编译的
gcc -pthread test.c -o test
在pthread_create()
之后和return EXIT_SUCCESS;
之前插入pthread_join(a, NULL)
以确保子线程在main()
之前完成 returns.
pthread_join()
是一种方法,但不是 唯一的 解决方案。
如果您的主线程不(需要)存活更长时间(比它创建的线程),它可以简单地退出 pthread_exit(0)
。
当主线程使用 pthread_exit()
退出时,进程将保持活动状态,直到进程中的 last 线程退出。
这在主线程执行 initialization/setup 并启动多个线程时非常有用,然后就不再需要了。
否则,它将不得不等待 all 个线程完成(请记住,当 main() 退出时,整个进程退出 - 调用 pthread_exit()
将仅退出 main 线程,不是整个进程)。