这里的想法是创建一个要写入的文件。我试图创建十个线程并让它们分别打印到文件10次。使用信号量可以阻止多个线程一次写入文件。但我有错误。代码如下:
#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 我想写 怎么解决?
答案 0 :(得分:1)
我发现了一些事情:
您没有初始化您的信号量。使用 sem_init 执行此操作(并在完成后使用 sem_destroy )。
您没有加入自己的主题。程序将退出而不等待线程完成。您可以在循环中使用 pthread_join 来确保所有线程都已完成。
这是您的线程功能的更新版本。在生产代码中,我会检查我添加的函数的返回值。
void 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);
sem_init(&mutex,0,1);
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);
}
}
void* value = NULL;
for (i = 0; i < NUMBER_OF_THREADS; i++) {
pthread_join(threads[i], &value);
}
sem_destroy(&mutex);
}