线程同步

有时候我们需要用到线程同步来控制线程运行顺序。

复制代码
/***
synchro.c
***/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<pthread.h>
#include<errno.h>

void *func(void *arg)
{
    int threadno = *(int *)arg;
    int i = 0;
    for(; i < 10; i++)
    {
        printf("%d thread%d\n",threadno,i);
        sleep(1);
    }
    return NULL;
}

int main()
{
    pthread_t t1,t2;
    int i = 1,j = 2;
    pthread_create(&t1,NULL,func,&i);
    pthread_create(&t2,NULL,func,&j);
    
    pthread_join(t1,NULL);    
    pthread_join(t2,NULL);

    printf("main exit\n");
    return EXIT_SUCCESS;
}
复制代码

exbot@ubuntu:~/wangqinghe/thread/20190729$ ./synchro

2 thread0

1 thread0

2 thread1

1 thread1

2 thread2

1 thread2

2 thread3

1 thread3

2 thread4

1 thread4

2 thread5

1 thread5

2 thread6

1 thread6

2 thread7

1 thread7

2 thread8

1 thread8

2 thread9

1 thread9

main exit

线程1和线程2互相抢占资源。

用互斥的方式来控制只有一个线程来使用资源。

复制代码
/***
lock.c
***/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<pthread.h>
#include<errno.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void *func(void *arg)
{

    pthread_mutex_lock(&mutex);    

    int threadno = *(int *)arg;
    int i = 0;
    for(; i < 10; i++)
    {
        printf("%d thread%d\n",threadno,i);
        sleep(1);
    }
    pthread_mutex_unlock(&mutex);
    return NULL;
}

int main()
{
    pthread_t t1,t2;
    int i = 1,j = 2;
    pthread_create(&t1,NULL,func,&i);
    pthread_create(&t2,NULL,func,&j);
    
    pthread_join(t1,NULL);    
    pthread_join(t2,NULL);

    printf("main exit\n");
    return EXIT_SUCCESS;
}
复制代码

运行结果:

exbot@ubuntu:~/wangqinghe/thread/20190729$ ./synchro1

2 thread0

2 thread1

2 thread2

2 thread3

2 thread4

2 thread5

2 thread6

2 thread7

2 thread8

2 thread9

1 thread0

1 thread1

1 thread2

1 thread3

1 thread4

1 thread5

1 thread6

1 thread7

1 thread8

1 thread9

main exit

 

线程2先进入后一直运行到任务结束,对mutex解锁后线程1才进入。

PTHREAD_MUTEX_INITIALIZER 是初始化一个快速锁的宏定义。

Pthread_mutex_t = PTHREAD_MUTEX_INITIALIZER

 

加锁解锁函数:

int pthread_mutex_lock(&mutex);

int pthread_mutex_unlock(&mutex);

posted @   王清河  阅读(176)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2018-07-29 1002 A+B for Polynomials (25)
2018-07-29 1001 A+B Format (20)
点击右上角即可分享
微信分享提示