这里的想法是创建一个要写入的文件。我正在尝试创建十个线程并让它们每个打印到文件 10 次。使用信号量来阻止多个线程一次写入文件。一切都编译了,我没有收到错误退出,但是我不明白为什么要多次运行程序:1)它不会在文件中打印 100 行,实际上它要少得多 2)打印到的行数文件每次都不同。
#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;
}
我的主要功能包含在一个单独的文件中。