ここでのアイデアは、書き込むファイルを作成することです。私は10スレッドを作成しようとしていると、彼らはそれぞれ10回ファイルに印刷する。セマフォを使用して、複数のスレッドが同時にファイルに書き込むのを止めます。しかし、私には誤りがあります。以下のコードは次のとおりです。20スレッドを使用してファイルに書き込む
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define FNAME "fisier.txt"
#define MAX_STRING_LEN 80
#define NUMBER_OF_THREADS 10
FILE *fp;
sem_t mutex;
int counter;
FILE *makeTextFile(char *fname, char mode){
FILE *localFP;
localFP = fopen(fname, &mode);
return (localFP);
}
void *print_message(void *tid){
int i;
for (i = 0; i < 10; i++){
sem_wait(&mutex);
fp = fopen(FNAME, "a");
fprintf(fp, "Thread %d is running.\n", tid);
fclose(fp);
sem_post(&mutex);
printf ("Thread %d has finished.\n", tid);
}
}
int threads(){
const char *fName = "fisier.txt";
int status;
pthread_t threads[NUMBER_OF_THREADS];
fp = makeTextFile(FNAME, 'w');
fprintf(fp, "Process ID: %ld\n", (long)getpid());
fclose(fp);
int i;
for (i =0; i < NUMBER_OF_THREADS; i++){
status = pthread_create(&threads[i], NULL, &print_message, (void *)i);
if (status != 0){
printf("pthread_create returned error code %d\n", status);
exit(-1);
}
}
}
int main() {
threads();
return 0;
}
警告:
probl2.c: In function ‘print_message’:
probl2.c:27:21: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘void *’ [-Wformat=]
fprintf(fp, "Thread %d is running.\n", tid);
^
probl2.c:30:14: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘void *’ [-Wformat=]
printf ("Thread %d has finished.\n", tid);
^
probl2.c: In function ‘threads’:
probl2.c:44:68: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
status = pthread_create(&threads[i], NULL, &print_message, (void *)i);
書き込みファイルにそれは:プロセスID:10568 私はそれを解決するためにどのように を書きたいですか?
'int'を' void * 'にキャストするのに賢明だったので、 'void *'を 'int'にキャストしてください。そしてそれらはエラーではなく、警告です。それでも、彼らに注意を払うためにあなたに良い。 – StoryTeller
最後の警告は、 '' ... ... '(void *)(intptr_t)i'と'(int)(intptr_t)tid'から 'intptr_t'にキャストすることで避けることができます。ちょっと不器用ですが、警告を無効にすることなく警告を取り除く方法です。 –
セマフォを初期化していません。 –