user1762121
user1762121

Reputation: 25

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

Upvotes: 0

Views: 3286

Answers (2)

Donald
Donald

Reputation: 124

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.E.g:

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();
}

Upvotes: 0

shawn
shawn

Reputation: 336

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.

Upvotes: 1

Related Questions