参考出处:http://www.cnblogs.com/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 "); pthread_t tid1, tid2; int rc1 = 0; int rc2 = 0; rc2 = pthread_create( &tid2, NULL, thread2, NULL ); if ( 0 != rc2 ) { printf("%s: %d ", __func__, strerror(rc2) ); } rc1 = pthread_create( &tid1, NULL, thread1, NULL ); if ( 0 != rc1 ) { printf( "%s: %d ", __func__, strerror( rc1 ) ); } printf( "leave main " ); getchar(); exit( 0 ); } void* thread1( void* arg ) { printf( "Enter thread1 " ); printf( "This is thread1, g_Flag : %d, thread id is %u ", g_Flag, ( unsigned int )pthread_self() ); g_Flag = 1; printf( "This is thread1, g_Flag : %d, thread_id is %u ", g_Flag, ( unsigned int )pthread_self() ); printf( "leave thread " ); pthread_exit( 0 ); } void* thread2( void* arg ) { printf( "Enter thread2 " ); printf( "This is thread2, g_Flag : %d, thread_id is %u ", g_Flag, (unsigned int )pthread_self() ); g_Flag = 2; printf( "This is thread2, g_Flag :%d, thread_id is %u ", g_Flag, (unsigned int )pthread_self() ); pthread_exit( 0 ); }