在C程序中使用多线程写入并输出到文件中

问题描述 投票:0回答:1

我是C语言的新手,正在尝试学习多线程。我用一个计数为100000的C程序(带有2个线程)并输出到文本来播放声音。但是,我的程序似乎有段。故障。我想不明白。请帮助:)

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define COUNT_TO 100000
#define MAX_CORES 2

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
long long i = 0;


void *start_counting(FILE *out) 
{
    //lock
    pthread_mutex_lock(&mutex);

    while (i < COUNT_TO) 
    {
        ++i;

        printf("i = %lld\n", i);
        fprintf(out,"i = %lld\n", i);
    }

    //lock
    pthread_mutex_unlock(&mutex);
}


int main(void) 
{
    int i = 0;

    FILE *out;
    out = fopen("output.txt","w");

    // create a thread group the size of MAX_CORES
    pthread_t *thread_group = malloc(sizeof(pthread_t) * MAX_CORES);

    // start all threads to begin work
    for (i = 0; i < MAX_CORES; ++i) 
    {
        pthread_create(&thread_group[i], NULL, start_counting(out), NULL);
    }

    // wait for all threads to finish
    for (i = 0; i < MAX_CORES; ++i) 
    {
        pthread_join(thread_group[i], NULL);
    }

    fclose(out);

    return EXIT_SUCCESS;
}
c multithreading
1个回答
0
投票

您在此通话中出错:

pthread_create(&thread_group[i], NULL, start_counting(out), NULL);

应该是:

pthread_create(&thread_group[i], NULL, start_counting, out);

请参阅https://man7.org/linux/man-pages/man3/pthread_create.3.html的手册

© www.soinside.com 2019 - 2024. All rights reserved.