码迷,mamicode.com
首页 > 编程语言 > 详细

pthread_mutex_lock线程锁使用简单示例

时间:2014-12-16 19:16:01      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:pthread_mutex_lock 多

#define __USE_LARGEFILE64
#define _LARGEFILE64_SOURCE
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <pthread.h>
#include "../errors.h"
#define mutex_lock


pthread_mutex_t mutex;
void *thread_function_even(void *inpara)
{
    int *num = (int *)inpara;
    long unsigned int thread_num = pthread_self();
    pthread_detach( thread_num ); /*detach to be an independent thread*/
    while(1)
    {
#ifdef mutex_lock
        pthread_mutex_lock(&mutex);
#endif
        *num = (*num * 2)% 100;
        usleep(1);
        printf("int thread_function_even,num:%d,is even:%d\n",*num, (0 == *num % 2) );
#ifdef mutex_lock
        pthread_mutex_unlock(&mutex);
#endif
    }
}
void *thread_function_odd(void *inpara)
{
    int *num = (int *)inpara;
    long unsigned int thread_num = pthread_self();
    pthread_detach( thread_num ); /*detach to be an independent thread*/
    while(1)
    {
#ifdef mutex_lock
        pthread_mutex_lock(&mutex);
#endif
        *num = (*num * 2)% 100 + 1;
        usleep(1);
        printf("int thread_function_odd,num:%d,is even:%d\n",*num, (0 == *num % 2) );
#ifdef mutex_lock
        pthread_mutex_unlock(&mutex);
#endif
    }
}
int main (int argc, char *argv[])
{
    /*mutex is a lock,everyone only can operate an array by get the mutex*/
#ifdef mutex_lock
    pthread_mutex_init(&mutex, NULL);
#endif


    /*create two threads,one change the num to even,the other change the num to odd*/
    int i = 0;
    pthread_t thread_even,thread_odd;
    pthread_create(&thread_even, NULL, thread_function_even, &i);
    pthread_create(&thread_odd, NULL, thread_function_odd, &i);


    while(1);
#ifdef mutex_lock
    pthread_mutex_destroy(&mutex);
#endif

}

1.编译:gcc main.c -lpthread -g

2.运行:./a > 1 十几秒后ctrl c停掉

3.验证锁是否有效,以下两条命令都搜不到结果:

cat 1|grep thread_function_odd|grep "even:1"
cat 1|grep thread_function_even|grep "even:0"

4.去掉代码中的锁:注释#define mutex_lock

5.去掉后验证不加锁后是否正确,步骤3中的两条命令能搜到结果

cat 1|grep thread_function_odd|grep "even:1"
cat 1|grep thread_function_even|grep "even:0"

6.代码的原理:创建两个线程,两个线程都操作同一个整数,一个只把整数变为偶数,一个只把整数变为奇数,加锁的情况下,偶数线程中打印的数字全为偶数,奇数线程中打印的数字全为奇数

pthread_mutex_lock线程锁使用简单示例

标签:pthread_mutex_lock 多

原文地址:http://blog.csdn.net/oywoywoyw/article/details/41963487

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!