UNIX Environment Programming Learning notes (26)-multithreaded programming (i): Creating and terminating threads

Source: Internet
Author: User

Lienhua34
2014-11-08

In the Process Control trilogy we learned the process Control primitives of process creation, termination, and getting the terminating state. The control of the thread is similar to the control of the process, and in table 1 we list the control primitives corresponding to the process and line threads.

Table 1: Comparison of process primitives and line Hodohara
Process Primitive Line Hodohara language Describe
Fork Pthread_create Create a new control flow
Exit Pthread_exit Exiting from an existing control flow
Waitpid Pthread_join Get exit status from the control flow
Atexit Pthread_cleanup_push Registers the function that is called when exiting the control flow
Getpid Pthread_self Gets the ID of the control flow
Abort Pthread_cancel Non-normal exit of request control flow
1 threads

Each thread has a thread ID, and the thread is only valid in the process environment to which it belongs. The thread ID is expressed using pthread_t. You can get the thread ID of the thread itself by calling the Pthread_self function.

#include <pthread.h>

pthread_t pthread_self (void);

Return value: Thread ID of the calling thread

The thread ID is not necessarily a non-negative integer, or it may be a struct. So, to compare whether two threads are the same, you must use the Pthread_equal function,

#include <pthread.h>

int pthread_equal (pthread_t tid1, pthread_t Tid2);

Return value: Returns a value other than 0 if equal, otherwise 0

2 Creation of threads

You can create a new thread by calling Pthread_create.

#include <pthread.h>

int pthread_create (pthread_t *restrict TIDP, const pthread_attr_t *restrict attr, void * (*START_RTN) (void *), void *restri CT Arg);

Return value: Returns 0 if successful, otherwise the error code is returned

Where the parameter TIDP is used to return the thread ID of the new thread that was created successfully. The parameter attr is used to customize various thread properties, and if set to NULL, represents a thread that creates a default property. A new thread that was created successfully starts execution from the function pointed to by the parameter Start_rtn, which receives a void * argument arg and returns a void * return value.

Note: The error code returned when Pthread_create failed indicates that we can get the specific error message by calling the Strerror function.

Let's look at an example of creating a new process,

#include <stdlib.h>#include<stdio.h>#include<string.h>#include<pthread.h>void*My_thread (void*Arg) {printf ("In new Thread. Tid:%u\n", (unsignedint) pthread_self ()); return((void*)0);}intMain (void){  interr;  pthread_t Tid; Err= Pthread_create (&tid, NULL, my_thread, NULL); if(Err! =0) {printf ("can ' t create thread:%s\n", Strerror (err)); Exit (-1); } printf ("In main thread:%u\n", (unsignedint) pthread_self ()); Sleep (1); Exit (0);}

Compile the program, generate and execute the file Pthread_create_demo. From the running results below, we can see that the thread ID printed in the main function and the My_thread function is not the same.

gcc -o pthread_create_demo-pthread pthread_create_demo.clienhua34:demo$. /Pthread_create_demoin3076478720in3076475712
3 Thread Termination

If any thread in the process calls the Exit, _exit, or _exit functions, the entire process will be terminated. So what if we just want to terminate a thread alone? There are three ways to

1. The thread returns from the startup routine and the return value is the thread's exit code.

2. Canceled by another thread in the same process.

3. Thread Call function Pthread_exit.

The declaration of the Pthread_exit function is as follows

#include <pthread.h>

void Pthread_exit (void *rval_ptr);

Other threads in the process can get the exit code for the specified thread by calling Pthread_join.

#include <pthread.h>

int Pthread_join (pthread_t tid, void **rval_ptr);

Return value: Returns 0 if successful, otherwise returns the error number

The Pthread_join function causes the calling thread to block until the specified thread terminates. If the specified thread is only returned from its startup routine, Rval_ptr will contain the return code. If the thread is canceled, the memory unit specified by RVAL_PTR will be set to pthread_canceled.

Let's take a look at an example of a thread termination,

#include <stdlib.h>#include<stdio.h>#include<string.h>#include<pthread.h>void*Thr_fn1 (void*Arg) {printf ("In thread 1\n"); return((void*)1);}void*thr_fn2 (void*Arg) {printf ("In thread 2\n"); Pthread_exit ((void*)2);}intMain (void){  interr;  pthread_t Tid1, Tid2; void*Tret; Err= Pthread_create (&tid1, NULL, THR_FN1, NULL); if(Err! =0) {printf ("can ' t create thread 1:%s\n", Strerror (err)); Exit (-1); } Err= Pthread_create (&Tid2, NULL, THR_FN2, NULL); if(Err! =0) {printf ("can ' t create thread 2:%s\n", Strerror (err)); Exit (-1); } Err= Pthread_join (TID1, &Tret); if(Err! =0) {printf ("can ' t join with thread 1:%s\n", Strerror (err)); Exit (-1); } printf ("Thread 1 exit code:%d\n", (int) Tret); Err= Pthread_join (Tid2, &Tret); if(Err! =0) {printf ("can ' t join with thread 2:%s\n", Strerror (err)); Exit (-1); } printf ("Thread 2 exit code:%d\n", (int) Tret); Exit (0);}
pthread_exit_demo.c

Compile the program, generate and execute the file Pthread_exit_demo,

gcc -o pthread_exit_demo-pthread pthread_exit_demo.clienhua34:demo$. /Pthread_exit_demoin1in211  2 2

(done)

UNIX Environment Programming Learning notes (26)-multithreaded programming (i): Creating and terminating threads

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.