Close the thread when done with it

How do you close the stream when done? How to make sure that nothing else opens or starts?

So far I know how to open it, but .. not how to close it correctly

int iret1; pthread_t thread1; char *message1; void *multithreading1( void *ptr ) { while (1) { // Our function here } } int main (int argc, char * const argv[]) { if( (iret1=pthread_create( &thread1, NULL, multithreading1, (void*) message1)) ) { printf("Thread creation failed: %d\n", iret1); } return 0; } 
+6
source share
2 answers

"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 
+7
source

To do this, you either return from the thread function ( multithreading1 ) or call pthread_exit() .

See POSIX Threads Programming for more information.

+7
source

Source: https://habr.com/ru/post/917037/


All Articles