Basic Control of multi-thread programming in Linux
Basic thread control
1. thread creation
Int pthread_create (pthread_t * pid, pthread_attr_t * attr, void * (start_routine) (void *), void * arg );
Pthread_create creates a thread. this thread will execute the start_routine function. the parameters of this function are provided by arg. you can call pthread_exit to terminate the thread or
Stops when the function is executed. Attr is a thread attribute. it is set to NULL for the moment.
Each process shares an address space and resources. Unlike the fork process, each process has its own address space and resources.
If the execution succeeds, 0 is returned. if the execution fails, non-0 is returned.
2. obtain the thread ID.
Pthread_t * pthread_self ();
3. end thread
Void pthread_exit (void * retval );
Retval is the return value for executing the function. if the function is successful, it is 0. if the function fails, it returns-1.
4. thread suspension
Int pthread_join (pthread_t * tid, void ** thread_return );
This function is used to suspend a thread until it is terminated. tid indicates the thread id, and thread_return indicates the return value of the thread.
5. Demo
| 123456789101112131415161718192021222324252627282930313233343536 |
/** =================================================== ========================================================== =========** Filename: main. c ** Description: I ** Version: 1.0 * Created: 02/18/2013 10:46:58 * Revision: none * Compiler: gcc ** Author: WuShuai, * Blog: imsiren.com * Organization: ** ===================================================== ========================================================== =======*/# include # Include # Include Voidrunner (void * arg) {pthread_t t = pthread_self (); printf ("thread id: % x \ n", (unsignedint) t);} intmain () {intarg = 1000; void * ret; pthread_t tid [2]; pthread_create (& tid [1], NULL, (void *) & runner, (void *) arg ); pthread_create (& tid [2], NULL, (void *) & runner, (void *) arg); pthread_join (tid [1], & ret ); pthread_join (tid [2], & ret); return0 ;} |
Compile:
Gcc-g-o thread main. c-lpthread
Result:
[Root @ s thread] #./thread
Thread id: b6d72b70
Thread id: b7773b70