【问题标题】:Pthreads program with mutex - printing same string every time带有互斥锁的 Pthreads 程序 - 每次打印相同的字符串
【发布时间】:2019-06-15 16:31:10
【问题描述】:

我有一个学校项目,需要我编写一个程序来打印:<ONE><TWO><THREE><ONE><TWO><THREE><ONE><TWO><THREE>….............. 使用 3 个线程和互斥锁。我试图在课堂上的一些帮助下做到这一点,但它只是继续打印<ONE>。你能帮我解决我的问题并理解我有什么问题吗?

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

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void *func(void *arg)
{
    pthread_mutex_lock(&mutex);
    while (1) {
        printf ("<ONE>");
    }
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

void *func2(void *arg)
{
    pthread_mutex_lock(&mutex);
    while (1) {
        printf ("<TWO>");
    }
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

void *func3(void *arg)
{
    pthread_mutex_lock(&mutex);
    while (1) {
        printf ("<THREE>");
    }
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

main()

{
    pthread_t mythread1,mythread2,mythread3;

    pthread_create( &mythread1, NULL, func, (void *) 1);
    pthread_create( &mythread2, NULL, func2, (void *) 2);
    pthread_create( &mythread3, NULL, func3, (void *) 3);

    pthread_join ( mythread1, NULL);
    pthread_join ( mythread2, NULL);
    pthread_join ( mythread3, NULL);

    exit(0);
}

【问题讨论】:

  • 您希望循环while(1) { printf("&lt;ONE&gt;"); } 何时停止?
  • 你只能使用一个互斥锁吗?
  • @klutt 问题在于它不会停止。我希望它停止,然后是 ,然后是 ,然后再重复一遍。我做错了什么, 循环永远不会停止。我必须使用多少互斥锁没有限制。只是因为我不熟悉他们我用了一个
  • 是的,我只是指出一个明显的事实,即由于您从未解锁互斥锁,它将陷入无限循环。您必须在循环内锁定和解锁它。
  • @klutt 好的。现在它只是随机打印 。不是我想要的顺序

标签: c multithreading pthreads mutex thread-synchronization


【解决方案1】:

正如我在 cmets 中明确指出的那样,这将陷入无限循环,因为您正在循环之外进行锁定和解锁。第一步是将它们移到里面。

void *func(void *arg)
{
    while (1) {
        pthread_mutex_lock(&mutex);
        printf ("<ONE>");
        pthread_mutex_unlock(&mutex);
   }
   pthread_exit(NULL);
}

接下来,我们需要添加同步。一个简单的方法是声明一个全局变量:

int next = 1; 

然后我们这样修改函数:

void *func(void *arg)
{
    while (1) {
        while(1) {
            pthread_mutex_lock(&mutex);
            if(next == 1) break;
            pthread_mutex_unlock(&mutex);
        }

        printf ("<ONE>");

        next = 2;

        pthread_mutex_unlock(&mutex);
   }
   pthread_exit(NULL);
}

func2func3 中,您需要将if(next == 1)next = 2 修改为适当的值。 func2 应该有 2 和 3,而func3 应该有 3 和 1。

这种方法称为忙等待,通常不是最佳选择,因为它对 cpu 非常密集。更好的选择是查看pthread_cond_wait()。你可以在这里阅读:http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_cond_wait.html

【讨论】:

    猜你喜欢
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    相关资源
    最近更新 更多