线程运动。交替打印两个不同线程的ID

时间:2017-05-21 23:05:00

标签: c linux multithreading pthreads

我必须编写一个程序,创建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);    
       }
*/

正如你所看到的,我尝试过多种策略,但都没有成功。

1 个答案:

答案 0 :(得分:0)

忘记互斥。

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

主题A:

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

主题B:

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

看看使用正确的同步对象有多容易?