失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 多线程之:主线程 子线程

多线程之:主线程 子线程

时间:2024-04-21 23:08:00

相关推荐

多线程之:主线程 子线程

1、进程中线程之间的关系

线程不像进程,一个进程中的线程之间是没有父子之分的,都是平级关系。即线程都是一样的, 退出了一个不会影响另外一个。

但是所谓的"主线程"main,其入口代码是类似这样的方式调用main的:exit(main(...))

main执行完之后, 会调用exit()

exit()会让整个进程over终止,那所有线程自然都会退出。

2、主线程先退出,子线程继续运行的方法

在进程主函数(main())中调用pthread_exit(),只会使主函数所在的线程(可以说是进程的主线程)退出;而如果是return,编译器将使其调用进程退出的代码(如_exit()),从而导致进程及其所有线程结束运行。

理论上说,pthread_exit()和线程宿体函数退出的功能是相同的,函数结束时会在内部自动调用pthread_exit()来清理线程相关的资源。但实际上二者由于编译器的处理有很大的不同。

按照POSIX标准定义,当主线程在子线程终止之前调用pthread_exit()时,子线程是不会退出的。

When you program with POSIX Threads API, there is one thing about pthread_exit() that you may ignore for mistake. In subroutines that complete normally, there is nothing special you have to do unless you want to pass a return code back using pthread_exit(). The completion won’t affect the other threads which were created by the main thread of this subroutine. However, in main(), when the code has been executed to the end, there could leave a choice for you. If you want to kill all the threads that main() created before, you can dispense with calling any f

unctions.But if you want to keep the process and all the other threads except for the main thread alive after the exit of main(), then you can call pthread_exit() to realize it. And any files opened inside the main thread will remain open after its termination.

main()中调用了pthread_exit后,导致住线程提前退出,其后的exit()无法执行了,所以要到其他线程全部执行完了,整个进程才会退出。

c#子线程与主线程之间该怎么通信

先说明一下,本人最近遇到了什么问题,就是在写写消息队列的时候,发现消息队列每次接收一个消息的时候都是创建了一个新的线程。这样就导致了消息处理的时候没有在主线程上进行,然而其中的一些步事项是要通过主线程才能操作的。这样就引出了一个子线程怎么去通知主线程要做哪些事情呢?

为了解决上面的问题我找了好的多资料,好多都是用委托,去解决了,然后我又看了我的项目通过这种beginInvoker的这种办法解决不是很好用。并不能解决的当前的问题,在这个时候我发现了SynchronizationContext对象。这个对像的用处就是可以记录一个线程的上下文然后再子线程处理完之后,要用到主要程去操作的时候可以去Post或者Send一个事件支解决,这样就很方便,代码如下:

class TestClient{private Thread workThread;private SynchronizationContext mainThreadSynContext;public TestClient()//构造函数当然是主线程执行的{mainThreadSynContext = SynchronizationContext.Current; //在这里记录主线程的上下文workThread = new Thread(new ThreadStart(DoWork));//创建一个新的线程}private void OnConnected(object state)//由于是主线程的同步对象Post调用,这个是在主线程中执行的{//这里就回到了主线程里面了//做一些事情}private void DoWork()//这个是workThread线程执行的{//这儿做些事(连接什么的。。。)//这而干完了mainThreadSynContext.Post(new SendOrPostCallback(OnConnected), null);//通知主线程}}

如果觉得《多线程之:主线程 子线程》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。