简体   繁体   English

用多线程修改结构C编程

[英]modifying a struct with multiple threads c programming

I have been all over the internet with no one directly answering this question. 我到过互联网,没有人直接回答这个问题。 So I have a struct in my main process and I need multiple threads to modify it. 因此,我的主流程中有一个结构,并且需要多个线程对其进行修改。 I know that I am going to need mutexs to protect the data, but is there any way to share pointers with out passing it as an arg in pthread_create. 我知道我将需要互斥体来保护数据,但是有什么方法可以共享指针,而不必将其作为arg传递给pthread_create。 I understand that threads share the same memory address and there for if I allocate in one the other should have access to it. 我知道线程共享相同的内存地址,因此如果我分配一个内存地址,另一个应该可以访问它。 But with out passing a pointer how do the threads know that a certain pointer already exists. 但是在没有传递指针的情况下,线程如何知道某个指针已经存在。

The typical answer to your question is that rather than passing the pointer directly to the thread when you call pthread_create , you instead pass a pointer to some higher-level structure that serves as your communication with the thread. 该问题的典型答案是,调用pthread_create ,您无需将指针直接传递给线程,而是将指针传递给某个更高级别的结构,该结构可与线程进行通信。

For example, say you are writing a network server that receives requests from clients and then needs to process those requests. 例如,假设您正在编写一个网络服务器,该服务器接收来自客户端的请求,然后需要处理这些请求。 The threads that process requests from clients would typically be passed the address of some kind of waitable queue. 处理来自客户端的请求的线程通常会传递某种等待队列的地址。 When a thread receives a request from a client, it would put that request in the waitable queue. 当线程接收到来自客户端的请求时,会将请求放入等待队列。 The threads that process client requests are already waiting for things to be put on that queue, and they get the information about the request they need to process from the queue. 处理客户端请求的线程已经在等待将其放入该队列,并且它们从队列中获取有关需要处理的请求的信息。

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

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