Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中在线程之间传递消息_C_Multithreading_Pthreads - Fatal编程技术网

在C中在线程之间传递消息

在C中在线程之间传递消息,c,multithreading,pthreads,C,Multithreading,Pthreads,我想从主进程向每个线程发送一条消息,并在每个线程中打印“是”。我怎么做 我需要从主线程发送一条消息,然后在线程中打印并完成它 我得到了这个密码: #include <stdio.h> #include <pthread.h> #include <stdlib.h> void * thread1() { while(1){ printf("Hello!!\n"); } } void * thre

我想从主进程向每个线程发送一条消息,并在每个线程中打印“是”。我怎么做

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

我得到了这个密码:

#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周期就不会被占用


为了获得最佳安全性,主线程还可以在更新消息时锁定互斥锁,计数器可以使用PostThreadMessage,如本文所述。没有一条路是对的。您可以对每个线程使用一个队列。您可以使用共享队列,让每个线程跟踪最后处理的消息。你可以使用一个文件。你可以用管子。建议使用指示其编号的参数启动每个子线程,然后在子线程内部保留一个数组,其中每个子线程在数组[passed in parameter]条目中保留该子线程实例的任何本地数据。