在这段代码中,如何在不使用函数 pthread_join()
的情况下创建这些线程?使用 pthread_exit()
无效。
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
typedef struct{
char name[100];
char search[100];
pthread_t tid;
} mystruct;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
void* sfun(void *arg){
mystruct *sfile= (mystruct *) arg;
int fd=open(sfile->name,O_RDONLY);
if(fd<0){
printf("Error%s\n", sfile->name);
pthread_exit(NULL);
}
int n=1;
pthread_mutex_lock(&mutex);
while(n!=0){
n=match_line(fd,sfile->search);
printf("%s:\t%d\n",sfile->name,n);
}
pthread_mutex_unlock(&mutex);
close(fd);
return NULL;
}
int main(int argc, char *argv[]){
if(argc< 3){
printf("Error\n");
exit(1);
}
mystruct file[10];//max 10 threads
int c;
for(c=0;c<argc-2;c++){
strcpy(file[c].search,argv[1]);
strcpy(file[c].name,argv[c+2]);
pthread_create(&file[c].tid,NULL,sfun,&file[c]);
}
for(c=0;c<argc-2;c++)
pthread_join(file[c].tid,NULL);
return 0;
}
使用 pthread_join()
编译:
./ppc "Sherlock" testfile1 testfile2 testfile12
testfile1: 5
testfile1: 762
testfile1: 960
testfile1: 977
testfile1: 1025
testfile1: 1034
testfile1: 1049
testfile1: 1068
testfile1: 1080
testfile1: 1123
testfile1: 0
testfile2: 3
testfile2: 90
testfile2: 170
testfile2: 179
testfile2: 473
testfile2: 643
testfile2: 760
testfile2: 811
testfile2: 836
testfile2: 978
testfile2: 0
testfile12: 5
testfile12: 762
testfile12: 960
testfile12: 977
testfile12: 1025
testfile12: 1034
testfile12: 1049
testfile12: 1068
testfile12: 1080
testfile12: 1123
testfile12: 1129
testfile12: 1216
testfile12: 1296
testfile12: 1305
testfile12: 1599
testfile12: 1769
testfile12: 1886
testfile12: 1937
testfile12: 1962
testfile12: 2104
testfile12: 0
没有 pthread_join()
它不会打印任何东西!
最佳答案
您不使用 pthread_join
创建线程,而是使用 pthread_join
等待线程退出。
线程是进程的子单元:它们与同一进程中的其他线程在相同的内存空间中运行。结果,当进程结束时,属于它的任何正在运行的线程都将终止,并且退出 main(通过 exit 或 return)实质上结束了进程。
pthreads 没有用于从其进程中分离线程的 api。
如果这就是你想要做的,你将不得不创建进程,并且应该查看 posix_spawn
或 fork
/exec
.
如果您只是尝试创建线程,而不必显式地等待它们各自终止,您可以调用 pthread_exit
:http://man7.org/linux/man-pages/man3/pthread_exit.3.html
To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
void* tfun(void*)
{
sleep(3);
printf("Ni!\n");
return NULL;
}
int main()
{
pthread_t t;
pthread_create(&t,NULL,&tfun,NULL);
int ret = 0;
pthread_exit(&ret);
}
关于在 C 中创建没有 pthread_join 的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39584027/