首先介绍几个linux线程同步需要的函数:

pthread_mutex_lock();

pthread_mutex_unlock();

pthread_cond_wait();

pthread_cond_signal();


下面使用一个例子介绍上面几个函数的用法。在主线程接受用户输入信息,在子线程中输入用户输入的信息。

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t  mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  cond  =PTHREAD_COND_INITIALIZER;
pthread_t  pid;
int flag = 0;
char buf[1024];
void *print(void* arg)
{
        while(1)
        {
                pthread_mutex_lock(&mutex);
                if (flag == 1)
                {
                        printf("%s\n",buf);
                        flag = 0;
                }
                pthread_cond_signal(&cond);
                pthread_mutex_unlock(&mutex);
        }
}
int main()
{
        pthread_create(&pid,NULL,print,NULL);
        while(1)
        {
                pthread_mutex_lock(&mutex);
                printf("input->:");
                scanf("%s",buf);
                flag = 1;
                pthread_cond_wait(&cond,&mutex);
                pthread_mutex_unlock(&mutex);
        }
}

编译方法:

# gcc -lpthread  test.c

pthread_mutex_lock这个函数是获取互斥量。在这个线程没有执行pthread_mutex_unlock时,那么其他线程执行pthread_mutex_lock就会被阻塞。

pthread_cond_wait这个函数是将当前线程阻塞,并且释放互斥量。

pthread_mutex_signal函数是通知调用了pthread_cond_wait的函数,让它脱离阻塞,并且调用了pthread_cond_wait的线程将会重新获取互斥锁。




GitHub 加速计划 / li / linux-dash
12
2
下载
A beautiful web dashboard for Linux
最近提交(Master分支:2 个月前 )
186a802e added ecosystem file for PM2 5 年前
5def40a3 Add host customization support for the NodeJS version 5 年前
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐