简体   繁体   English

在C中使用信号量进行多线程处理

[英]Using semaphore for multithreading in C

The Idea here is to create a file to be written to. 这里的想法是创建一个要写入的文件。 I'm trying to create ten threads and have them print to the file 10 times each. 我正在尝试创建十个线程并让它们分别打印到文件10次。 Using a semaphore to stop multiple threads from writing to the file at once. 使用信号量可以阻止多个线程一次写入文件。 Everything compiles and I don't get an error exit, however I can't understand why running the program numerous times: 1)It doesn't print 100 lines to the file, infact it's far less 2) The number of lines printed to the file vary each time. 一切都编译,我没有错误退出,但我无法理解为什么多次运行程序: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;
   }

My main function is contained in a separate file. 我的主要功能包含在一个单独的文件中。

You need to wait for all thread to finish before you exit the program. 在退出程序之前,需要等待所有线程完成。

if you add trace you will see which thread is finish. 如果添加跟踪,您将看到哪个线程完成。

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);
 }
}

This is how you wait for all threads to finish 这就是你等待所有线程完成的方式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM