这里的想法是创建要写入的文件。我正在尝试创建10个线程,并将它们打印到每个文件10次。使用信号量来停止多个线程一次写入文件。一切都编译完成,我没有得到错误退出,但是我不明白为什么要多次运行该程序:1)它不会向文件打印100行,实际上它少得多2)打印到该文件每次都有所不同。在C中使用信号量进行多线程处理
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define READ "r"
#define NEW "w"
#define ADD "a"
#define NL "\n"
#define TAB "\t"
#define FNAME "PROCTAB.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, ADD);
fprintf(fp, "Thread %d is running.\n", tid);
fclose(fp);
sem_post(&mutex);
}
}
int threads(){
const char *fName = "PROCTAB.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);
}
}
return 0;
}
我的主要功能包含在一个单独的文件中。
测试'fp'在'FP = FOPEN(FNAME,ADD);',以确保你没有打开文件成功的所有时间你以为你做到了。还可以将fp局部化为'print_message()'。 – chux