linux 多線程基礎
參考出處:http://www.rzrgm.cn/skynet/archive/2010/10/30/1865267.html
1、進程與線程
進程是程序代碼在系統中的具體實現。進程是擁有所需資源和執行方案的集合。
線程是進程中劃分出的可獨立執行的一個控制流程。
兩者區別:
每個進程有各自獨立的地址空間。進程崩潰不會影響到其他進程。
所有線程共享同一進程的資源,除了局部變量和堆之外。線程的崩潰會導致所在進程的掛起。
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <errno.h> #include <unistd.h> int g_Flag = 0; void* thread1( void* ); void* thread2( void* ); int main( int argc, char* argv[] ) { printf(" Enter main\n "); pthread_t tid1, tid2; int rc1 = 0; int rc2 = 0; rc2 = pthread_create( &tid2, NULL, thread2, NULL ); if ( 0 != rc2 ) { printf("%s: %d\n", __func__, strerror(rc2) ); } rc1 = pthread_create( &tid1, NULL, thread1, NULL ); if ( 0 != rc1 ) { printf( "%s: %d\n", __func__, strerror( rc1 ) ); } printf( "leave main\n" ); getchar(); exit( 0 ); } void* thread1( void* arg ) { printf( "Enter thread1\n" ); printf( "This is thread1, g_Flag : %d, thread id is %u\n", g_Flag, ( unsigned int )pthread_self() ); g_Flag = 1; printf( "This is thread1, g_Flag : %d, thread_id is %u\n", g_Flag, ( unsigned int )pthread_self() ); printf( "leave thread\n" ); pthread_exit( 0 ); } void* thread2( void* arg ) { printf( "Enter thread2\n" ); printf( "This is thread2, g_Flag : %d, thread_id is %u\n", g_Flag, (unsigned int )pthread_self() ); g_Flag = 2; printf( "This is thread2, g_Flag :%d, thread_id is %u\n", g_Flag, (unsigned int )pthread_self() ); pthread_exit( 0 ); }
浙公網安備 33010602011771號