现在这只是一个小测试,也是学校作业的一部分。在我的代码中,printf 没有打印,至少我无法看到它。这是线程未运行的结果吗?打印线在线程外工作。感谢您的帮助。
我是 c 线程的新手。
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<stdlib.h>
void *threadServer(void *arg)
{
printf("This is the file Name: %s\n", arg);
pthread_exit(0);
}
int main(int argc, char* argv[]){
int i=1;
while(argv[i]!=NULL){
pthread_t thread;
pthread_create(&thread, NULL, threadServer,argv[i]);
i++;
}
最佳答案
在您的代码中,创建另一个线程的执行父线程无需等待其子线程完成即可完成执行。线程与进程不同,一旦父线程终止,其所有执行的子线程也将终止。
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
void *threadServer(void *arg)
{
printf("This is the file Name: %s\n", (char*)arg);
pthread_exit(0);
}
int main(int argc, char* argv[]){
int i=1;
while(argv[i]!=NULL){
pthread_t thread;
pthread_create(&thread, NULL, threadServer, argv[i]);
i++;
pthread_join(thread, NULL);
}
}
这样做将允许创建的线程运行,直到它完成执行。 pthread_join
将等待线程完成其执行,然后继续前进。
编辑
正如人们在评论中确实提到的那样,尝试生成一个线程并立即加入它可能毫无值(value),这使得它并不比一个执行线程更好。因此,为了实验方便,代码可以修改如下:
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
void *threadServer(void *arg)
{
printf("This is the file Name: %s\n", (char*)arg);
}
int main(int argc, char* argv[]){
int i = 1;
pthread_t thread[argc - 1];
while(i < argc)
{
pthread_create(&thread[i-1], NULL, threadServer, argv[i]);
i++;
}
for (i = 0; i < argc - 1; ++i)
{
pthread_join(thread[i], NULL);
}
}
关于C Printf 不在线程内部打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40822000/