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

线程同步技术

时间:2015-05-12 01:30:34      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

线程共享进程的内存空间,打开的文件描述符,全局变量。
当有多个线程同时访问一块内存空间或者一个变量、一个文件描述符,如果不加控制,那么可能会出现意想不到的结果。
 
互斥(mutex)是相互排斥的意思,它是一种锁或者信号灯。
互斥用来保护多个线程共享的数据和结构不会被同时修改,一个互斥锁只能有两个状态
  –locked---加锁
  –unlocked---解锁
加锁后互斥不让其他线程访问。
任何时刻只能有一个线程来掌握某个互斥上锁。
一个线程如果试图在一个已经加锁的互斥上再加锁,这个线程会被挂起,直到加锁的线程释放掉互斥锁为止。
 
 

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int pthread_mutex_lock(pthread_mutex_t *mutex);

int pthread_mutex_unlock(pthread_mutex_t *mutex);

PTHREAD_MUTEX_INITIALIZER是初始化一个快速锁的宏定义。
pthread_mutex_lock用于给mutex加锁。
pthread_mutex_unlock用于给mutex解锁。
 
 
没有线程同步例子
void *func(void *arg)
{
    int *a = (int *)arg;
    printf("thread%d start\n", *a);
    int i;
    for(i=0;i<10;i++)
    {
        printf("thread%d is running\n", *a);
        sleep(1);
    }
    printf("thread%d end\n", *a);
    pthread_exit(NULL);
}
int main(int arg, char * args[])
{
    printf("process start\n");
    pthread_t thr_d1, thr_d2;
    int i[2];
    i[0] = 1; i[1] =2;
    pthread_create(&thr_d1, NULL, func, &i[0]);
    pthread_create(&thr_d2, NULL, func, &i[1]);
    pthread_join(thr_d1, NULL);
    pthread_join(thr_d2, NULL);
    printf("process end\n");
    return 0;
}

 

使用mutex线程同步例子
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *func(void *arg)
{
    pthread_mutex_lock(&mutex);
    int *a = (int *)arg;
    printf("thread%d start\n", *a);
    int i;
    for(i=0;i<10;i++)
    {
        printf("thread%d is running\n", *a);
        sleep(1);
    }
    printf("thread%d end\n", *a);
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}
int main(int arg, char * args[])
{
    printf("process start\n");
    pthread_t thr_d1, thr_d2;
    int i[2];
    i[0] = 1; i[1] =2;
    pthread_create(&thr_d1, NULL, func, &i[0]);
    pthread_create(&thr_d2, NULL, func, &i[1]);
    pthread_join(thr_d1, NULL);
    pthread_join(thr_d2, NULL);
    printf("process end\n");
    return 0;
}

 

 

线程同步技术

标签:

原文地址:http://www.cnblogs.com/shichuan/p/4496162.html

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