c++ 如何给 "运行中" 的线程传递数据;
迷茫
迷茫 2017-04-17 14:01:09
0
4
636

1:场景是有一个线程池,我需要将任务队列中发生读写事件的fd拿出来传递到线程池
正常情况下创建线程时可以指定参数,比如这样

std::thread t(func,arg1,arg2,...)

但是我的fd是在线程已经创建好之后传入,那该怎么办?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(4)
Ty80

No special means are required to transfer data between threads, because most of the data of threads are shared. Global variables, static global variables and data passed through pointers can be shared directly between threads.
So the simplest way is to define a global queue so that every thread can access this queue. The main thread writes fd to the queue, and all threads in the thread pool take data from this queue. Of course, you can also pass the reference to the queue to each thread through parameters.
Considering that the queue of this C++ standard library is not thread-safe, you may need to use a lock to ensure the thread-safety of the queue.

大家讲道理

You can transfer it as you like, such as global variables, memory blocks on the heap, anything that is not tlsthread-local storage can be used for transmission, but the prerequisite is that it must be controlled by a lock.
You can choose mutex, etc. for read and write control.

小葫芦

What the thread pool receives is an operation, not a value... Even if the thread in the thread pool has been created, it is blocked in the queue... You only need to deliver an operation with fd to the thread pool...
If there is already an operation in the thread pool that is blocking and waiting for fd to come in, there will also be a condition variable to block the thread from running... When fd is ready, just notify the condition variable...

巴扎黑

PostThreadMessage can be considered under Windows.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template