简体   繁体   English

如何在pthread_create创建的子线程中调用主线程?

[英]How to call main thread in the child thread created by pthread_create?

I used pthread_create created a child thread for http requested,after i get the data i want to call the main thread to do some update of UI. 我使用pthread_create为请求的http创建了一个子线程,在获取数据后,我想调用主线程来进行UI更新。

pthread_detach();
pthread_exit();
pthread_join();

The three function which can use for that?Why? 那可以使用这三个功能呢?

Is there any warm-hearted person to solve my confusion? 有没有热情的人来解决我的困惑? A lot of thanks! 非常感谢!

The honest answer is none of the above. 诚实的答案不是以上所有。 There is no way to call the main thread from the child thread, but that does not mean you can't do what you are trying to. 无法从子线程中调用主线程,但这并不意味着您无法做您想做的事情。

A child thread shares the same memory space as the parent thread. 子线程与父线程共享相同的内存空间。 What you need to do is create a way for the child thread to inform the parent that it wants to send a message to the user (UI). 您需要做的是为子线程创建一种方法来通知父线程它希望向用户(UI)发送消息。 This could be done a number of different ways, but a simple method would be to provide a function that just takes the message you want to send and puts it onto a queue. 可以通过许多不同的方法来完成此操作,但是一种简单的方法是提供一个仅接收您要发送的消息并将其放入队列的功能。

The main thread would just need to check that queue occasionally for any messages and pull them off when it sees one on there to put onto the UI. 主线程只需要偶尔检查该队列中是否有任何消息,并在看到要放在UI上的消息时将其拉出。

You would of course need to make sure that pushing/popping from that queue was controlled with a mutex lock, but since we're talking about messages to the user it shouldn't be something you're doing too often and should not cause any real performance problems. 当然,您需要确保使用互斥锁来控制从该队列中的推送/弹出操作,但是由于我们正在与用户讨论消息,因此您不应经常这样做,也不应引起任何后果实际的性能问题。

As I mentioned, this is only one idea for how you could do this. 正如我提到的,这只是如何实现此目的的一个想法。 While there are many ways, the basic idea is that the threads need a way to communicate with each other. 尽管有很多方法,但是基本思想是线程需要一种相互通信的方法。

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

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