Matthew Habibi
Matthew Habibi

Reputation: 39

C - using pthread and waiting for a return value

I am currently working on a multi-client server that uses select() to handle multiple clients. However, when a client sends a message that needs heavy calculations, I have to create a a new thread using pthread_create() so that my server can remain responsive to other messages from clients. Once the calculation is done for that client, I need to be able to return a message to the client. But I am not sure how I can know if that thread is finished and how to get it's final result. Obviously I cant use pthread_join() as that blocks my server program while running that new thread. So does C offer a function that I can use to get the end result of that child thread? I would like to avoid using Global Variables as well.

Upvotes: 0

Views: 364

Answers (2)

caf
caf

Reputation: 239011

If you want the child thread to wake up the thread that is waiting in select() when it has finished processing, you can use pipe() to create a pipe. The thread calling select() adds the read side of the pipe to its file descriptor set, and the child thread writes to the write side of the pipe when it has finished its work.

You can even have it send the result over the pipe, if the result isn't too large.

Upvotes: 1

Petru
Petru

Reputation: 86

You can just check if the thread has finished before joining it from the main thread (which will be non blocking)

You should get how to do it from here : How do you query a pthread to see if it is still running?

Otherwise you can probably just send back the answer from the child thread, you can pass connection information as parameter of the thread function.

Upvotes: 1

Related Questions