Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Linux 多線程:三個子線程輪流輸出 A、B、C

這是迅雷的筆試題:

題目:編寫一個程式,開啟 3 個線程,ID 分別為 A、B、C,每個線程把自己的 ID 在螢幕上印 10 遍,要求輸出結果必須按 ABC 的順序顯示,例如 ABCABC…… 依次遞推。

程式碼

#include <pthread.h>
#include <cstdio>

const int THREAD_NUMBER = 3;

// 子線程的互斥量和條件變量
pthread_mutex_t thread_mutex[THREAD_NUMBER];
pthread_cond_t thread_cond[THREAD_NUMBER];

// 子線程是否正在等待
bool thread_wait_flag[THREAD_NUMBER];

// 標識輪到哪個子線程輸出其 ID
pthread_mutex_t mutex;
int thread_turn;

void *thread_func(void *arg);

int main(int argc, char **argv)
{
    pthread_t tids[THREAD_NUMBER];

    for (int i = 0; i < THREAD_NUMBER; ++i)
    {
        pthread_mutex_init(&thread_mutex[i], NULL);
        pthread_cond_init(&thread_cond[i], NULL);
    }

    pthread_mutex_init(&mutex, NULL);
    thread_turn = 0;

    for (int i = 0; i < THREAD_NUMBER; ++i)
        thread_wait_flag[i] = false;

    for (int i = 0; i < THREAD_NUMBER; ++i)
    {
        pthread_create(&tids[i], NULL, thread_func, (void *) i);
    }

    for (int i = 0; i < THREAD_NUMBER; ++i)
    {
        pthread_join(tids[i], NULL);
    }

    printf("\n");
    return 0;
}

void *thread_func(void *arg)
{
    int id = (int) arg;
    char ch = 'A' + id;
    int count = 0;

    while (true)
    {
        if (id == thread_turn)   // 若輪到當前子線程,輸出 ID 並發送信號
        {
            printf("%c", ch);
            ++count;
            if (id == THREAD_NUMBER - 1 && count == 10) // 第 3 個子線程輸出完可直接退出
                break;

            pthread_mutex_lock(&mutex);
            ++thread_turn;
            thread_turn %= THREAD_NUMBER;
            pthread_mutex_unlock(&mutex);

            while (true)
            {
                pthread_mutex_lock(&thread_mutex[thread_turn]);
                if (true == thread_wait_flag[thread_turn])
                {
                    pthread_cond_signal(&thread_cond[thread_turn]);
                    pthread_mutex_unlock(&thread_mutex[thread_turn]);
                    break;
                }
                pthread_mutex_unlock(&thread_mutex[thread_turn]);
            }

            if (count == 10)     // 第 1、2 個子線程發出信號後退出
                break;
        }
        else                     // 否則等待
        {
            pthread_mutex_lock(&thread_mutex[id]);
            thread_wait_flag[id] = true;
            pthread_cond_wait(&thread_cond[id], &thread_mutex[id]);
            thread_wait_flag[id] = false;
            pthread_mutex_unlock(&thread_mutex[id]);
        }
    }

    return (void *) 0;
}

解題關鍵

核心只有一個「令牌」變數 thread_turn:只有 id 等於 thread_turn 的線程才能輸出,輸出後立刻把令牌交給下一個(取模運算實現循環),然後設法喚醒對方。

這裡為每個線程配置獨立的 mutex 與 condition,比共用一個條件變量更精準,不會出現「喚醒了但不該執行」的驚醒效應。而 thread_wait_flag 的檢查,同樣是為了確保 signal 不會在對方進入 wait 之前就被消耗掉。

最後一個細節:C 先輸出完就 break,A、B 隨後也各自在 count 達到 10 時退出,因此三個線程都能正常結束,pthread_join 不會永遠等下去。

Copyright © Linux教程網 All Rights Reserved