gpt4 book ai didi

c - 在 C 中使用信号量进行多线程

转载 作者:太空宇宙 更新时间:2023-11-04 08:56:06 26 4
gpt4 key购买 nike

这里的想法是创建一个要写入的文件。我正在尝试创建十个线程并让它们分别打印到文件 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;
}

我的主要功能包含在一个单独的文件中。

最佳答案

在退出程序之前,您需要等待所有线程完成。

如果您添加跟踪,您将看到哪个线程已完成。

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);
printf ( "Thread %d has finished.\n", tid);
}
}

这是等待所有线程完成的方式

   /* Wait for Threads to Finish */
for (i=0; i<NUMTHREADS; i++) {
pthread_join(thread[i], NULL);
}

关于c - 在 C 中使用信号量进行多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16951013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com