简体   繁体   中英

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. The other thread is processing the data and sending the result to a server each 'X' period of time. 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. 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.

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.

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.

I hava meet the same question in a http-server, i get one thread to accept client-sockets, but distribute them to another thread. 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

waiting-thread

while(true){
    res = getInput();//block here
    rq->put(res);
}

=======================================

dealing-thread

while(true){
    while(rq.isEmpty()){
        usleep(100);
    }

    //not empty
    doYourWorks();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM