简体   繁体   English

C编程中的多线程写入和输出文件

[英]Writing and Outputing to File with Multi-Threading in C programing

I'm a novice in C and trying to learn Multi Threading.我是 C 的新手,正在尝试学习多线程。 I played aroud with a C program counting to 100000 with 2 threads and outputing to text.我玩了一个 C 程序,计数到 100000,有 2 个线程并输出到文本。 However, my program seem to have seg.但是,我的程序似乎有段。 fault.过错。 I cannot figure it out.我想不明白。 Please Help:)请帮忙:)

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

You have a error in this call:您在此调用中有错误:

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

It should be:它应该是:

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

Please refer to the manual at https://man7.org/linux/man-pages/man3/pthread_create.3.html请参阅手册https://man7.org/linux/man-pages/man3/pthread_create.3.html

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

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