Search code examples
multithreadingthreadpool

What does the main thread do in a thread pool /tasked based application?


In general, what does, or should the main thread be doing in a thread pool / tasked based application? Tasks are added to a queue, main thread decides which task to perform, once the tasks are working, should the main task pick up a task to perform? Should it sleep at all to avoid unneccessarily spinning, or would that be to risky to miss work/tasks?

In pseudocode/ this is my understanding:

main():
    # Lets say there are 4 threads in the pool
    init_thread_pool(4)
    while (1):
      # could either run (have the logic) in main() or run_thread_pool() 
      # Which task should run, are there any tasks at all
      run_thread_pool_tasks()
      # Should anything be done here? run a task? sleep? spin?
    

Solution

  • The main thread executes whatever code the programmer wrote for it to execute. I've seen Java Swing applications where the main thread creates some GUI objects on startup, and then it just ends—lets Swing take over. If a program needs a long-running thread, it can use the main thread for that. In some frameworks, the program ends if main() returns, and I've seen programs where main() just loops calling sleep() after everything else is initialized.