i program a multiclient instant messager server to improve my knowledge in using sockets and threads. At time i have for each client a thread, that is listening for incoming data and an other thread, that proceeds this data. The "Data Proceeding Thread => dpt" is proceeding a queue of tasks and each client thread can add new tasks into this queue. And here i have had an idea:
I want the current client thread to join the dpt, because while the task is in the queue this thread just sleeps and waits. Each client object pointer has a pointer to the clients thread and each client pointer is passed to the task struct, so i can access the client in my dpt thread.
For better understanding:
//While runnjing in the client_thread just call dpt->join()
client_thread->join(dpt)
//dpt->doTask
dpt->client->client_thread->detach()
While running the program, this do not work. Is it possible to do something like this or should i use the good old semaphores?
1) Are you using std::thread or some other threading library?
What are you trying to do here. Join and detach are two mutually exclusive operations:
joing makes current thread wait untill other will finish.
Detach detaches thread of execution from std::thread object making it run in background. You still need to make sure that it will finish before your program terminates or it will cause undefined behavior.
In both cases std::thread objects becomes unjoinable, allowing to destroy it safely.
I want, that the client_thread waits but not until the other is finished, the other thread should detach the client_thread and proceed => the client_thread should proceed up here too.
1) There is no sense to call joinWorker in a loop. You can only call join once on a thread. This code makes corresponding client_thread wait until worker finishes.
2) t->c->client_thread->detach(); detaching affects only std::thread object. It does not affect thread of execution itself, so any blocked client thread will still wait for worker to completely finish execution.
and start a new worker thread each time a new task will be add to the queue without that there is a working worker. In this case all client_threads will wait until the queue is finished (in worst case ALL client_threads). The result is, that each client has the same "priority".
An other way is to "lock" the client, so the client_thread waits until the client will be unlocked (sth. like semaphores).