簡體   English   中英

在C中的線程之間傳遞消息

[英]Pass message between threads in C

我想將消息從主進程發送到每個線程並打印(是,在每個線程中)。 我該怎么做?

我需要將消息從主服務器發送到線程,然后在線程中打印它並完成它。

我得到以下代碼:

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

void * thread1()
{
        while(1){
                printf("Hello!!\n");
        }
}

void * thread2()
{
        while(1){
                printf("How are you?\n");
        }
}

int main()
{
        int status;
        pthread_t tid1,tid2;

        pthread_create(&tid1,NULL,thread1,NULL);
        pthread_create(&tid2,NULL,thread2,NULL);
        pthread_join(tid1,NULL);
        pthread_join(tid2,NULL);
        return 0;
}

由於主線程和所有子線程都使用相同的數據,

主線程將一條消息以及一個“打印時間”計數器和一個消息號計數器放置在數據的緩沖區中。

0) Each sub thread is looping, watching that 'times to print' counter, 
when that counter becomes greater than 0,  then
checks if they have already output that message[number]
if they have NOT output that message then
1) save new message number
2) lock a mutex, 
3) prints the message, 
4) decrements the count of times that message to be printed, 
5) unlocks the mutex. 
branch back to 0)

0) The main thread is looping, waiting for the 'times to print' counter to reach 0. 


when it does reach 0, 
1) set the next message 
2) updates the 'times to print' counter,
3) increment the message number counter
if not all messages sent, then branch back to 0)

當然,子線程將需要某種指示,表明將不再有消息,這可能是通過主線程將“打印時間”計數器設置為-1來實現的。

注意:所有子線程都使用相同的互斥量

可能有必要將數據中的兩個計數器標記為“易失性”,以便子線程每次都檢索一個新副本。

建議每個線程在檢查“打印時間”計數器之間有一定的延遲,因此不要占用CPU周期

為了獲得最佳安全性,主線程還可以在更新消息和計數器時鎖定互斥鎖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM