在C中的2个线程中运行函数的问题

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

我已经编写了一个程序,该程序具有一个函数,该函数连续打印作为参数接收的字符,并使2个线程运行该函数。该程序将按预期运行,并无限期地打印2个字符。这是代码:

#include <pthread.h>
#include <stdio.h>
void* print_char(void* th_param) {
        char* ch = (char*)th_param;
        while(1)
                printf("%c", *ch);
        return NULL;
}
int main() {
        char* c1 = "a";
        char* c2 = "b";
        pthread_t th_id;
        pthread_create(&th_id, NULL, &print_char, (void*)c1);
        pthread_t th_id2;
        pthread_create(&th_id2, NULL, &print_char, (void*)c2);
        return 0;
}

现在,我必须修改此程序,以便print函数也接受数字参数,并以该次数打印字符。我尝试的是这样:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
struct Params {
        char* ch;
        int num;
};
void* print_char(void* th_param) {
        int i;
        struct Params* par = (struct Params*)th_param;
        for(i=0; i<par->num; i++) {
                printf("%s", par->ch);
        }
        return NULL;
}
int main() {
        struct Params* p1 = (struct Params*)malloc(sizeof(struct Params));
        p1->ch = "a"; p1->num = 5;
        struct Params* p2 = (struct Params*)malloc(sizeof(struct Params));
        p2->ch = "b"; p2->num = 10;
        pthread_t th_id;
        pthread_create(&th_id, NULL, &print_char, (void*)p1);
        pthread_t th_id2;
        pthread_create(&th_id2, NULL, &print_char, (void*)p2);
        while(1) {}
        return 0;
}

但无济于事。不打印单个字符,光标只是停留在那儿闪烁而无所事事。我已经尝试篡改代码数小时,但没有任何效果。请注意,该结构没有问题,因为如果我删除for循环并放入while(1)并再次无限次打印指定给par->ch的字符,该程序就可以工作。

我已经编写了一个程序,该程序具有一个函数,该函数连续打印作为参数接收的字符,并使2个线程运行该函数。程序按预期运行,并继续打印2 ...

c multithreading struct pthreads
2个回答
1
投票

问题是缓冲的I / O。


1
投票

由于您的while循环,stdout永远不会被刷新

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