线程同步错误-线程未向其他线程发出信号

时间:2019-03-09 20:19:28

标签: multithreading performance synchronization synchronized thread-synchronization

我的程序有问题。为了在学校进行练习,我尝试制作一个程序,该程序从输入中读取内容并将其放在输出中。就如此容易。但是,当我运行以下程序时,它似乎卡住了。我打印一些消息,它们通常取决于线程而最终如下:

  • 信号线程2
  • 等待线程1
  • 等待线程2

我不知道该怎么办。线程1应该向另一个线程发出信号,但是它们仍然以等待状态结束,尽管线程2收到了信号,但它并没有在while循环中中断。现在,当我在物理上更改num_of_chars和书面值的地方取消注释时,它确实起作用。该程序似乎仍然运行缓慢。 如果您有任何想法,为什么不起作用,为什么pthread_cond_signal似乎不起作用,请告诉我。另外,如果您知道该程序的运行速度会更快,我将非常满意。 :) 程序

#define V  300

pthread_cond_t loading;
pthread_cond_t write_down;
pthread_mutex_t mutex;
char a[V];
int num_of_chars = 0;
int written = 0;


void *input() {

    while(1){
        pthread_mutex_lock(&mutex);

        while(num_of_chars > 0){
            printf("waiting for a signal from thread2");
            fflush(stdout);
            pthread_cond_wait(&loading, &mutex);        
        }
        num_of_chars = fread(a, sizeof(char), V, stdin);

        if(num_of_chars == 0){
            //written = 3;
            pthread_mutex_unlock(&mutex);
            pthread_cond_signal(&write_down);
            pthread_exit(NULL);
        }
        if(num_of_chars <= V){
            printf("signalizing thread2");
            fflush(stdout);
            //written = 3;
            pthread_cond_signal(&write_down);
        }
        pthread_mutex_unlock(&mutex);
    }

}

void *output() {
    while(1){
        while(written == 0){
            printf("waiting for a signal from thread1");
            fflush(stdout);
            pthread_cond_wait(&write_down, &mutex); 
        }
        written = fwrite(a, sizeof(char), num_of_chars, stdout);
        fflush(stdout);

        if(num_of_chars == 0){
            pthread_mutex_unlock(&mutex);
            pthread_exit(NULL);
        }
        if(num_of_chars > 0){
            printf("signalizing thread1");
            fflush(stdout);
            //written = 0;
            //num_of_chars = 0;
            pthread_cond_signal(&loading);

        }
        pthread_mutex_unlock(&mutex);
    }
}

int main (void) {
    pthread_t t1, t2; 

    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init (&loading, NULL);
    pthread_cond_init (&write_down, NULL);

    pthread_create(&t1, NULL, input,  NULL);
    pthread_create(&t2, NULL, output,  NULL);


    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    /*pthread_mutex_destroy(&mutex);
    pthread_cond_destroy (input);
    pthread_cond_destroy(output);*/
    return 0;
}

0 个答案:

没有答案