The*_*and 3 c multithreading pthreads
现在这只是一个小测试,也是学校作业的一部分。在我的代码中, 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++;
}
Run Code Online (Sandbox Code Playgroud)
在您的代码中,创建另一个线程的父执行线程无需等待其子线程完成即可完成执行。线程与进程不同,一旦父线程终止,其所有执行的子线程也将终止。
#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);
}
}
Run Code Online (Sandbox Code Playgroud)
这样做将允许创建的线程运行,直到它完成执行。在pthread_join将等待线程完成执行,然后继续前进。
编辑
正如人们在评论中确实提到的那样,尝试生成单个线程并立即加入它可能毫无价值,使其不比单个执行线程好。因此,为了实验起见,可以将代码修改如下:
#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);
}
}
Run Code Online (Sandbox Code Playgroud)