Reputation: 11
In a simple example of multithreaded processing/moving of data, two threads are created: One thread reads the data from shared memory, the other writes it to a file. Are there advantages to moving the read out of main and into a thread of its own? In this case main is not doing anything once the threads are created, so why would you or would you not want to do the read() in main()?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
// Create a shared memory object.
int shm_fd = shm_open("/dev/shm/my_shm", O_RDWR, 0666);
// Map the shared memory object into the process's address space.
void *ptr = mmap(NULL, 1024, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
// Create a buffer to store the data from the shared memory object.
char buffer[1024];
// Create a thread to read data from the shared memory object.
pthread_t read_thread;
pthread_create(&read_thread, NULL, read_data, ptr);
// Create a thread to write data to the microSD card file.
pthread_t write_thread;
pthread_create(&write_thread, NULL, write_data, buffer);
// Wait for the threads to finish.
pthread_join(read_thread, NULL);
pthread_join(write_thread, NULL);
// Close the shared memory object.
close(shm_fd);
return 0;
}
void *read_data(void *ptr) {
// Read data from the shared memory object.
read(ptr, buffer, 1024);
return NULL;
}
void *write_data(void *ptr) {
// Write data to the microSD card file.
write(ptr, buffer, 1024);
return NULL;
}
Upvotes: 1
Views: 89
Reputation: 386541
[I will be ignoring the problems with the reader and the writers themselves since the question wasn't about them, and they are probably just poorly-written placeholders for more complex code. These problems were addressed by comments.]
You are correct.
You could replace
pthread_t read_thread;
pthread_create(&read_thread, NULL, read_data, ptr);
pthread_t write_thread;
pthread_create(&write_thread, NULL, write_data, buffer);
pthread_join(read_thread, NULL);
pthread_join(write_thread, NULL);
with
pthread_t write_thread;
pthread_create(&write_thread, NULL, write_data, buffer);
read_data(ptr);
pthread_join(write_thread, NULL);
You could even replace it with
pthread_t read_thread;
pthread_create(&read_thread, NULL, read_data, ptr);
write_data(buffer)
pthread_join(read_thread, NULL);
Switching would save a modicum of additional resources, but you'd lose the symmetry (which is particularly useful in a teaching environment). Using an additional thread also saves from having to decide which function to call in the main thread.
Upvotes: 0
Reputation: 24
What you are describing resembles the Consumer Producer Problem which have well established solutions. Using threads will depend on your problem and your devices. Some questions you could ask yourself would be:
And very important, when working with threads, always take care of synchronizing
Upvotes: -1