Reputation: 744
I need to design a system where there are two Threads T1 and T2 where T1 submits the results and T2 reads the results.
What is the most efficient way of defining a Data Structure that can be used to design such system ? There is no shared memory that can be accessed between the threads and there is a restriction of the usage of memcpy in case if we copy the result .
The result structure is defined as
typedef struct
{
UINT32 ot_id;
BOOLEAN result;
} RESULT;
Thanks in advance.
Upvotes: 0
Views: 389
Reputation: 8576
( THIS ANSWER IS VALID AS LONG AS YOU ARE ON A UNIX/UNIX-LIKE PLATFORM! )
Although by definition the existence of threads implies shared memory, you can go the weirdo way and use pipes instead.
The function pipe()
is declared in <unistd.h>
. It takes a int[2]
as parameter, and returns an error code int
(0
is success, failure otherwise). If successful, the function creates two new file descriptors, one for reading and other for writing. Whenever you write in the write-only file descriptor, that data arrives at the read-only file descriptor! That mechanism is known as a pipe. If you try to read in the read-only file descriptor, but the data is still not there, the read()
function will simply block (unless instructed to do otherwise by means of fcntl()
).
For any int fd[2]
, pipe(fd)
sets fd[0]
to the read end and fd[1]
to the write end.
Now, what you can do is call pipe
before spawning the second thread, and pass fd[0]
as an argument to it, so it can read the data! Let's see an example (note, no error checking!)...
#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;
}
Upvotes: 1
Reputation: 715
> 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.
Upvotes: 0