简体   繁体   English

主线程在基于线程池/任务的应用程序中做什么?

[英]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?
    

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.我见过 Java Swing 应用程序,其中主线程在启动时创建一些 GUI 对象,然后它就结束了——让 Swing 接管。 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.在某些框架中,如果 main() 返回,程序就会结束,我见过这样的程序,其中 main() 只是在其他所有内容初始化后循环调用sleep()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM