pthread_mutex_lock线程锁使用简单示例

来源:互联网 发布:vb中boolean什么意思 编辑:程序博客网 时间:2024/06/05 02:12
#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>
#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.代码的原理:创建两个线程,两个线程都操作同一个整数,一个只把整数变为偶数,一个只把整数变为奇数,加锁的情况下,偶数线程中打印的数字全为偶数,奇数线程中打印的数字全为奇数

0 0
原创粉丝点击