【问题标题】:Threads exercise. Print alternately the ids of two distinct threads线程练习。交替打印两个不同线程的 id
【发布时间】:2017-10-21 12:11:07
【问题描述】:

我必须编写一个程序来创建 2 个线程来打印它们自己的 ID,然后完成。
线程必须交替打印它们的 ID(A、B、A、B、...)。

void *funct();
//void *functz();
//int functie=0;

pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;

int main(){
        int rc1, rc2;
        pthread_t thread1, thread2;

    if( (rc1 = pthread_create(&thread1, NULL, &funct, NULL)) )
        {
                printf("Eroare la creare thread: %d \n", rc1);
        }
        if( (rc2 = pthread_create(&thread2, NULL, &funct, NULL)) )
        {
                printf("Eroare la creare thread: %d \n", rc2);
        }
        pthread_join (thread1, NULL);
        pthread_join (thread2, NULL);

        return 0;
}

void *funct()
{
        int i;
        //pthread_mutex_lock(&mutex1);
        for( i=0; i<10; i++)
        {
        //pthread_mutex_lock(&mutex1);
        //pthread_mutex_lock(&mutex2);
                printf("Thread ID: %li \n", pthread_self() );

        //pthread_mutex_unlock(&mutex2);
        //pthread_mutex_unlock(&mutex1);
        }
    //pthread_mutex_unlock(&mutex1);
}
/*
void *functz()
{
        int i;
        //pthread_mutex_lock(&mutex1);
        for( i=0; i<10; i++)
        {
        pthread_mutex_lock(&mutex2);

                printf("Thread ID: %li \n", pthread_self() );

        pthread_mutex_lock(&mutex1);    
       }
*/

如您所见,我尝试了多种策略,但都没有成功。

【问题讨论】:

  • 欢迎来到 Stack Overflow。请花时间阅读The Tour 并参考Help Center 中的材料,您可以在这里问什么以及如何问。
  • 调试器是解决此类问题的正确工具。 询问 Stack Overflow 之前,您应该逐行逐行检查您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 edit 您的问题包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
  • 你忘了问问题。另外:不成功是什么意思?您的编译器或链接器是否给您一个错误(哪一个)?程序在运行时是否崩溃(调试器说什么)?它没有打印正确的输出(它打印了哪个输出)?
  • @πάνταῥεῖ 公平地说,调试多线程程序非常困难。
  • 除了互斥量之外,你还知道哪些同步原语?如何使用它们?

标签: c linux multithreading pthreads


【解决方案1】:

忘记互斥锁。

使用两个信号量,例如 semRunA,初始化为 1 个单位,semRunB,初始化为 0 个单位。然后交换一个“执行令牌”:

线程 A:

while(true){
  wait(semRunA);
  print(threadID);
  post(semRunB);
};

线程 B:

while(true){
  wait(semRunB);
  print(threadID);
  post(semRunA);
};

看看使用正确的同步对象是多么容易吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多