带互斥锁的Pthreads程序-每次打印相同的字符串

时间:2019-06-15 16:31:10

标签: c multithreading pthreads mutex thread-synchronization

我有一个学校项目,要求我编写一个程序来打印此内容:<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);
}

1 个答案:

答案 0 :(得分:1)

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

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