doubleE
doubleE

Reputation: 1073

C file descriptor, Poll and thread

Assume I have couple of sockets I want to monitor. If I create POSIX file descriptors on each of them and assign an event handler to each file descriptor structure, Do I need to create and assign thread to each socket?

My understanding is that whenever an event occurs on a defined file descriptor, its event handler function will be called. So threads are not required. Am I right?

Upvotes: 1

Views: 1286

Answers (1)

nsilent22
nsilent22

Reputation: 2863

The simple answer to your question "Do I need to create and assign thread to each socket?" is "No". Threads are perfect way to shoot yourself in the foot.

But look at this part: "[...] whenever an event occurs on a defined file descriptor, its event handler function will be called [...]". And now answer the questions: Who will call the event handler? How your program would notice, that an event occurred?

Of course you can make every thread for every descriptor and just "sit" on them with e.g. blocking read function. And then die a terrifying death trying to synchronize with your main thread.

But better solution is to make one of your main-loop steps to check for events (e.g. using select or poll functions), and then, for every descriptor that is "active" to call it's handler from the main-loop. If the processing in the handler is not time-consuming you can stay away from the threads at a safe distance.

Upvotes: 3

Related Questions