Linux线程函数学习

说明: 

   1.  使用gcc编译时 应该加上 -lpthread , 如: gcc pthread_test.c -o out -lpthread

   2.  对于线程锁,如果没有加锁,就直接解锁,则相当于没有加锁,不会编译出错.


代码如下:

#include <stdio.h>  
#include <time.h>
#include "pthread.h"
#include <stdlib.h>

void  fun_thread1( char* msg );  
void  fun_thread2( char* msg );  
int g_value = 1;

pthread_mutex_t mutex;  

/* in the thread individual, the thread reset the g_value to 0,and add to 5 int the thread1,add to 6 in the thread2. */  
int main(int argc, char * argv[])  
{  
    pthread_t thread1;  
    pthread_t thread2;  
    if(pthread_mutex_init(&mutex,NULL) != 0 )  
    {  
       printf("Init metux error.\n");  
        exit(1);  
      }  
    if(pthread_create(&thread1,NULL, (void *)fun_thread1 ,NULL) != 0)  
    {  
          printf("Init thread1 error.\n");  
          exit(1);  
    }  
    if(pthread_create(&thread2,NULL,(void *)fun_thread2,NULL) != 0)  
    {  
        printf("Init thread2 error.\n");  
        exit(1);  
   }  
   sleep(1);  
    printf("I am main thread, g_vlaue is %d.\n",g_value);  
    return 0;  
}  
void  fun_thread1( char* msg )  
{  
    int val;  
    val = pthread_mutex_lock(&mutex);/*lock the mutex*/  
    if(val != 0)  
   {  
        printf("lock error.\n");  
    }  
    g_value = 0;/*reset the g_value to 0.after that add it to 5.*/  
   printf("thread 1 locked,init the g_value to 0, and add 5.\n");  
    g_value += 5;  
    printf("the g_value is %d.\n",g_value);  
    pthread_mutex_unlock(&mutex);/*unlock the mutex*/  
    printf("thread 1 unlocked.\n");  
}  
void  fun_thread2(char* msg)  
{     
   int val;  
   val = pthread_mutex_lock(&mutex);/*lock the mutex*/  
   if(val != 0)  
   {  
        printf("lock error.\n");  
    }  
    g_value = 0;/*reset the g_value to 0.after that add it to 6.*/  
    printf("thread 2 locked,init the g_value to 0, and add 6.\n");  
    g_value += 6;  
    printf("the g_value is %d.\n",g_value);  
    pthread_mutex_unlock(&mutex);/*unlock the mutex*/  
    printf("thread 2 unlocked.\n");  
}  


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值