0

I'm writing code to save text to a binary file, which includes a function to auto-save text to the binary file, as well as a function to print from the binary file, and I need to incorporate pthread locks and join. We were given

 pthread_mutext_t mutex;
 pthread_t autosavethread;

as global variables, although the instructor didn't talk about what pthread or mutex actually do, so I'm confused about that. Also, I understand that I need to use locks whenever shared variables are changed or read (in my case it would be the binary file). But at the end of the file I am supposed to use pthread_join, and I don't know what it does or what arguments are supposed to be used in it. I'm guessing mutex and autosavethread are supposed to be closed, or something along the lines of that, but I don't know how to write it. Can anyone help better my understanding?

alk
  • 69,737
  • 10
  • 105
  • 255
Madison Rubia
  • 19
  • 1
  • 3
  • 1
    Find a pthreads tutorial on the web. There are many. There are also thousands of answers here demonstrating the creation and joining of threads and the appropriate usage of mutexes. Your intuition of what you have to do is correct. If you have problems with your code you can return with specific questions. – Duck Jun 05 '14 at 02:27
  • If you are on Linux box you may want to use `man functionName` in terminal to get information about particular function. – Łukasz Daniluk Jun 05 '14 at 07:50

1 Answers1

1

There are two types of pthread - joinable thread & detached thread. If you want to let a thread just take a task and go away once the task is done, you need the detached thread; If you want to have the communication with the created thread when that thread is done with the assigned job, you have to use joinable thread. Basically it's needed when the parent & its created thread need to communicate after the thread is done.

It's very to google what exactly you need to call the pthread APIs and what can be communicated.

But one thing i want to mention here is, for the joinable thread, you have to explicitly call the pthread_join against the created thread. Otherwise, there will be serious memory leaks. When the joinable thread completes its task, the thread seems to exit (On linux, you can check the /proc/PID/task/ folder and once the thread completes, the entry under it will go away), but the resource allocated for this joinable thread, i.e. stack, is still there in the process memory space. As more and more joinable threads created and completing their tasks, the stacks for each thread are just left in process space, unless you explicitly call the pthread_join. Hope that helps, even a bit