簡體   English   中英

C中帶有pthreads的printf

[英]printf with pthreads in C

我現在正在使用pthreads處理生產者/消費者問題。 目前,我只是想讓生產者正常工作,並使用printf語句查看問題所在。 問題是代碼可以很好地編譯,但是當我運行它時,它什么也沒做,只是看起來運行得很好。 我嘗試將第一行設置為printf語句,但即使這樣也無法打印。 我也嘗試過使用fflush,但是我的想法已經用完了。 我的問題為什么連第一個printf語句也被跳過?

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

void *producer();

pthread_mutex_t lock;
pthread_cond_t done, full, empty;
int buffer[10];
int in = 0, out = 0;
int min = 0, max = 0, numOfItems = 0, total = 0;
double avg;


void *producer() {
    srand(time(NULL));
    int n = rand();
    int i;
    for(i = 0; i < n; i++)
    {
        int random = rand();
        pthread_mutex_lock(&lock);
        buffer[in++] = random;
        if(in == 10)
        {
            pthread_cond_signal(&full);
            printf("Buffer full");
            pthread_mutex_unlock(&lock);
            sleep(1);
        }
    }
    pthread_exit(NULL);
}

void *consumer() {
    pthread_exit(NULL);
}
int main(int argc, char *argv[]){
    printf("test");
    //Create threads and attribute
    pthread_t ptid, ctid;
    pthread_attr_t attr;

    //Initialize conditions and mutex
    pthread_cond_init(&full, NULL);
    pthread_cond_init(&empty, NULL);
    pthread_cond_init(&done, NULL);
    pthread_mutex_init(&lock, NULL);

    //Create joinable state
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    pthread_create(&ptid, &attr,(void *)producer,NULL);
    pthread_create(&ctid, &attr,(void *)consumer,NULL);


    pthread_join(ptid,NULL);
    pthread_join(ctid,NULL);

    printf("Program Finished!");
    pthread_exit(NULL);
}
man pthread_mutex_init

pthread_mutex_init初始化互斥對象根據在mutexattr指定的互斥鎖屬性指向的互斥 如果MutexattrNULL ,則使用默認屬性。

LinuxThreads實現僅支持一種互斥鎖屬性,即互斥鎖種類 ... 互斥鎖的種類決定了是否可以由已經擁有該互斥鎖的線程再次對其進行鎖定。 默認類型是快速 ...

如果互斥鎖已被調用線程鎖定,則pthread_mutex_lock的行為取決於互斥鎖的類型。 如果互斥鎖是快速類型的,則調用線程將被掛起,直到互斥鎖被解鎖為止,從而有效地導致了調用線程死鎖。

那就是您的制作人發生的事情:它在通話中陷入僵局

    pthread_mutex_lock(&lock);

-除了在極小的情況下n <2-外,不會產生任何輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM