c - C 线程间传递消息

标签 c multithreading pthreads

我想从主进程向每个线程发送一条消息并打印它(是的,在每个线程中)。我该怎么做?

我需要从master发送一条消息到线程,然后在线程中打印它并完成。

我得到了这个代码:

#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

注意:所有子线程都使用相同的互斥体

可能需要将数据中的两个计数器标记为“ volatile ”,以便子线程每次都会检索新的副本。

建议每个线程在检查“打印次数”计数器之间有一定的延迟,这样 CPU 周期就不会被占用

为了获得最佳安全性,主线程也可以在更新消息和计数器时锁定互斥体

关于c - C 线程间传递消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33379789/

相关文章:

python - 使用 Tornado 为我的 Python 应用程序提供一个 Web 界面来监控它

创建 gtk 信号以编辑在其他线程中运行的 GtkWidget

c++ - 测量互斥量争用/解释互斥量输出

将 unix 时间转换为日期

将元素添加到固定长度数组并删除第一个元素的干净方法?

c - 为什么要为该数组中的第一个元素打印垃圾?

使用一行 telnet 语句时,C 套接字读取输出空字符串

java - 无状态 session bean 中的多线程?

ruby-on-rails - 如何捕获线程中的错误,然后在所有线程完成后重新抛出该错误?

c++ - 有什么区别。 C++ 中的 getpid 和 gettid 之间