[英]How to pass data from one thread to another running thread using pthread in C++
Is there a way to pass data from one running thread to another running thread. 有没有一种方法可以将数据从一个正在运行的线程传递到另一个正在运行的线程。 One of the threads shows a menu and the user selects one option using cin. 线程之一显示菜单,用户使用cin选择一个选项。 The other thread is processing the data and sending the result to a server each 'X' period of time. 另一个线程正在处理数据,并在每个“ X”时间段内将结果发送到服务器。 As I can wait the whole program in the cin instruction waiting for the user to input the data, I divided the program into two threads. 因为我可以在cin指令中等待整个程序等待用户输入数据,所以我将该程序分为两个线程。 The data input of the menu is used in the other thread. 菜单的数据输入在另一个线程中使用。
Thanks 谢谢
As far as I know, with pthreads there is no direct way of passing any arbitrary data from one thread to another. 据我所知,使用pthreads并没有直接方法将任意数据从一个线程传递到另一个线程。
However, threads share the same memory space; 但是,线程共享相同的内存空间。 and as a result one thread can modify an object in the memory, and the other one can read it. 结果,一个线程可以修改内存中的对象,而另一个线程可以读取它。 To avoid race conditions, the access to this shared-memory object requires synchronization using a mutex. 为了避免争用条件,需要使用互斥锁来同步访问此共享内存对象。
Thread #1: when user responds: locks mutex, modifies the object and unlocks mutex. 线程1:用户响应时:锁定互斥锁,修改对象并解锁互斥锁。
Thread #2: every "x" period of time: locks the mutex, reads the object state, unlocks mutex and then does its processing based on the object state. 线程2:每个“ x”时间段:锁定互斥锁,读取对象状态,解锁互斥锁,然后根据对象状态进行处理。
I hava meet the same question in a http-server, i get one thread to accept client-sockets, but distribute them to another thread. 我在http服务器中遇到了同样的问题,我得到一个线程来接受客户端套接字,但是将它们分发给另一个线程。 My suggestion is that , the waiting-thread and dealing-thread use a same queue, and you pass a pointer of the queue to both thread, the waiting-thread write data into the queue when there are user inputting, and the dealing-thread sleeps untill the queue is not empty.Eg: 我的建议是,等待线程和处理线程使用相同的队列,并且将队列的指针传递给两个线程,等待线程在有用户输入时将数据写入队列,并且处理线程休眠直到队列不为空。例如:
ring_queue rq;//remember to pass the address of rq to waiting_thread & dealing_thread ring_queue rq; //记住将rq的地址传递给waiting_thread和dealing_thread
waiting-thread 等待线程
while(true){
res = getInput();//block here
rq->put(res);
}
======================================= ======================================
dealing-thread 处理线程
while(true){
while(rq.isEmpty()){
usleep(100);
}
//not empty
doYourWorks();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.