POSIX线程同步

简介: 在posix编程中,如果在不同的线程中几乎同一时间操作同一个变量的时候,就会出现不同步。如何解决这样的问题,这里需要用到互斥量,互斥锁的概念。请看UNIX环境高级编程P299页#include #include #include //线程1 void *thread_func1(v...

在posix编程中,如果在不同的线程中几乎同一时间操作同一个变量的时候,就会出现不同步。

如何解决这样的问题,这里需要用到互斥量,互斥锁的概念。请看UNIX环境高级编程P299页

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
//线程1 
void *thread_func1(void *arg);
//线程2 
void *thread_func2(void *arg);
pthread_mutex_t lock ;
int count = 0 ;
int main(void)
{
	pthread_t  tid1,tid2 ;
	pthread_create(&tid1 , NULL , thread_func1 , 0);
	pthread_create(&tid2 , NULL , thread_func2 , 0);
	//互斥锁初始化 
	pthread_mutex_init(&lock , NULL);
	count = 0 ;
	while(1)
	{	
		//加锁 
		pthread_mutex_lock(&lock);
		sleep(1);
		printf("count:%d\n",count);
		//解锁 
		pthread_mutex_unlock(&lock);
	}
	return 0 ; 
}
void *thread_func1(void *arg)
{
	while(1)
	{
		pthread_mutex_lock(&lock);
	//	sleep(1);
		count++ ; 
		pthread_mutex_unlock(&lock);
	}
}

void *thread_func2(void *arg)
{
	while(1)
	{
		pthread_mutex_lock(&lock);
	//	sleep(1);
		count++ ; 
		pthread_mutex_unlock(&lock);
	}
}
目录
相关文章
|
6天前
|
Linux C++
LInux下Posix的传统线程示例
LInux下Posix的传统线程示例
21 1
|
6天前
|
Unix API 调度
POSIX线程基本操作
POSIX线程基本操作
37 0
|
6天前
|
数据挖掘 API 数据处理
POSIX线程私有空间
POSIX线程私有空间
28 0
|
8月前
|
存储 安全 Linux
Posix多线程编程
Posix多线程编程
48 0
|
Linux
Linux Qt使用POSIX多线程条件变量、互斥锁(量)
Linux Qt使用POSIX多线程条件变量、互斥锁(量)今天团建,但是文章也要写。酒要喝好,文要写美,方为我辈程序员的全才之路。嘎嘎 之前一直在看POSIX的多线程编程,上个周末结合自己的理解,写了一个基于Qt的用条件变量同步线程的例子。
1345 0
18.pthread POSIX线程
(创建于 2018/3/1 上午7:11:44) 查看pthread所有方法 man -k pthread 输出结果 pthread_attr_destroy (3) - initialize and destroy thread attribute...
980 0
通用线程:POSIX 线程详解pthread_mutex_lock
POSIX 线程是提高代码响应和性能的有力手段。在此三部分系列文章的第二篇中,DanielRobbins 将说明,如何使用被称为互斥对象的灵巧小玩意,来保护线程代码中共享数据结构的完整性。
916 0