linux 多线程基础

时间:2025-04-06 08:07:25

参考出处: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 = ; void* thread1( void* );
void* thread2( void* ); int main( int argc, char* argv[] )
{
printf(" Enter main\n "); pthread_t tid1, tid2;
int rc1 = ;
int rc2 = ; rc2 = pthread_create( &tid2, NULL, thread2, NULL );
if ( != rc2 )
{
printf("%s: %d\n", __func__, strerror(rc2) );
} rc1 = pthread_create( &tid1, NULL, thread1, NULL );
if ( != rc1 )
{
printf( "%s: %d\n", __func__, strerror( rc1 ) );
}
printf( "leave main\n" ); getchar(); exit( );
} 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 = ;
printf( "This is thread1, g_Flag : %d, thread_id is %u\n", g_Flag, ( unsigned int )pthread_self() );
printf( "leave thread\n" );
pthread_exit( );
} 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 = ;
printf( "This is thread2, g_Flag :%d, thread_id is %u\n", g_Flag, (unsigned int )pthread_self() );
pthread_exit( );
}