"How do you close the stream when you're done?"
Either a simple return from this function, or a call to the pthread_exit function .
Note that the return
call also causes the stack to unwind, and the variables declared in the initial routine are destroyed, so this is more preferable than the pthread_exit
function:
An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it. The function return value shall serve as the thread exit status.
For more information, see also return () versus pthread_exit () in pthread startup functions
"make sure nothing else opens or starts
Instead of making sure your thread is still running, you should wait for it to finish using the pthread_join function .
Here is an example:
void *routine(void *ptr) { int* arg = (int*) ptr; // in C, explicit type cast is redundant printf("changing %d to 7\n", *arg); *arg = 7; return ptr; } int main(int argc, char * const argv[]) { pthread_t thread1; int arg = 3; pthread_create(&thread1, NULL, routine, (void*) &arg); int* retval; pthread_join(thread1, (void**) &retval); printf("thread1 returned %d\n", *retval); return 0; }
Exit
changing 3 to 7 thread1 returned 7
source share