linux 多线程基础

参考出处: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\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 );
}

 

 

转载于:https://www.cnblogs.com/bracken/p/3141649.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值