參考出處:http://www.cnblogs.com/skynet/archive/2010/10/30/1865267.htmlhtml
進程是程序代碼在系統中的具體實現。進程是擁有所需資源和執行方案的集合。spa
線程是進程中劃分出的可獨立執行的一個控制流程。線程
二者區別:code
每一個進程有各自獨立的地址空間。進程崩潰不會影響到其餘進程。htm
全部線程共享同一進程的資源,除了局部變量和堆以外。線程的崩潰會致使所在進程的掛起。blog
#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 ); }