【问题标题】:printf with pthreads in Cprintf 与 C 中的 pthreads
【发布时间】:2013-12-05 15:33:15
【问题描述】:

我现在正在使用 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);
}

【问题讨论】:

  • 你说程序运行,是什么意思?它是否像无限循环一样运行?它会立即退出而没有错误吗?
  • 如果“它什么也没做,但似乎运行得很好”是你的测试,我可以很容易地编写出许多优秀的程序。 :) 换句话说:你不是很清楚,很难理解你的意思。
  • 控制台输出可能是行缓冲的。在字符串末尾添加\n,如果要使用printf 进行调试,请使用fflush(stdout)
  • 如果in != 10你没有解锁互斥锁
  • 在哪里检查线程创建是否成功?那你怎么知道它成功了。线程默认是可连接的。

标签: c pthreads


【解决方案1】:
man pthread_mutex_init

pthread_mutex_init初始化mutex指向的互斥对象 根据 mutexattr 中指定的互斥属性。如果 mutexattrNULL,使用默认属性代替。

LinuxThreads 实现只支持一个互斥属性,即 mutex kind...互斥锁的种类决定了它是否可以被再次锁定 一个已经拥有它的线程。默认类型是fast...

如果互斥锁已被调用线程锁定,则 pthread_mutex_lock 取决于互斥体的类型。如果互斥锁是 fast 类型,调用线程被挂起,直到互斥体 解锁,从而有效地导致调用线程死锁。

这就是你的生产者发生的事情:它在调用中死锁

    pthread_mutex_lock(&lock);

- 除非在不太可能的情况下 n - 因此不会产生任何输出。

【讨论】:

    猜你喜欢
    • 2019-03-17
    • 2011-01-25
    • 2021-08-10
    • 2017-01-09
    • 2021-12-26
    • 2014-06-21
    • 2017-07-18
    • 1970-01-01
    相关资源
    最近更新 更多