我需要设计一个系统,其中有两个线程T1和T2,其中T1提交结果,T2读取结果。
定义可用于设计此类系统的数据结构的最有效方法是什么?线程之间没有可以访问的共享内存,如果我们复制结果,则会限制memcpy的使用。
结果结构定义为
typedef struct
{
UINT32 ot_id;
BOOLEAN result;
} RESULT;
提前谢谢。
(只要您在UNIX/UNIX-LIKE平台上,此答案就有效!)
尽管根据定义,线程的存在意味着共享内存,但您可以采取奇怪的方式,使用管道。
函数pipe()
是在<unistd.h>
中声明的。它以一个int[2]
作为参数,并返回一个错误代码int
(0
表示成功,否则为失败)。如果成功,该函数将创建两个新的文件描述符,一个用于读取,另一个用于写入。无论何时写入只读文件描述符,数据都会到达只读文件描述符!这种机制被称为管道。如果您尝试读取只读文件描述符,但数据仍然不存在,则read()
函数将简单地阻塞(除非通过fcntl()
指示执行其他操作)。
对于任何int fd[2]
,pipe(fd)
将fd[0]
设置为读取端,将fd[1]
设置为写入端。
现在,您可以做的是在生成第二个线程之前调用pipe
,并将fd[0]
作为参数传递给它,这样它就可以读取数据了!让我们看一个例子(注意,没有错误检查!)。。。
#include <unistd.h>
typedef struct {
UINT32 ot_id;
BOOLEAN result;
} RESULT;
void secondThread(int readDescriptor) {
RESULT result;
read(readDescriptor, &result, sizeof(RESULT));
// Do something with that...
close(readDescriptor);
}
int main() {
int fd[2];
pipe(fd);
spawnTheSecondHolyThread(secondThread, fd[0]);
RESULT result;
// Calculate the result...
write(fd[1], &result, sizeof(result));
close(fd[1]);
joinTheSecondThread();
return 0;
}
> Use queue.
> 1. create the queue and call the method that will produce(submit) data to the queue.
> 2. create a new thread that will read the data from the queue.
> 3. use mutex or any else mechanism to protect the queue heads. Else you can go lock free queue implementation.
>
> Let me know if you need any code.