このコードセグメントでは、関数pthread_join()
を使用せずにこれらのスレッドを作成するにはどうすればよいですか? pthread_exit()
を使用しても機能しませんでした。 pthread_join()
でコンパイルCでpthread_joinのないスレッドを作成
#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を呼び出さずにスレッドを作成できます。本当の質問は何ですか? – immibis
@immibisこの特定のケースでは、スレッドは実行を終了しません。つまり、最後まで実行されません。しかし、pthread_join()はそれを実行します。 – sh1ftz
はい、この特定のケースでは、スレッドが終了する前にプログラムが終了するためです。 – immibis