#include <iostream>
#include <pthread.h>
#include <stdio.h>
//用c++简单的封装互斥锁
class LOCK
{
private:
pthread_mutex_t mutex;
public:
LOCK();
virtual ~LOCK();
void lock_t();
void unlock_t();
void trylock_t();
};
LOCK::LOCK()
{
pthread_mutex_init(&mutex, NULL); //在构造函数中直接初始化互斥锁
}
LOCK::~LOCK()
{
}
void LOCK::lock_t()
{
pthread_mutex_lock(&mutex);
}
void LOCK::unlock_t()
{
pthread_mutex_unlock(&mutex);
}
void LOCK::trylock_t()
{
pthread_mutex_trylock(&mutex);
}
//全局变量
int a = 0;
//创建锁对象
LOCK lock;
//线程回调函数
void * thread1(void * arg)
{
while(1)
{
printf("I am thread1\n");
lock.lock_t();
a++;
printf("thread1-a === %d\n",a);
lock.unlock_t();
sleep(1);
}
}
void * thread2(void *arg)
{
while(1)
{
printf("I am thread2\n");
lock.lock_t();
a++;
printf("thread2-a === %d\n",a);
lock.unlock_t();
sleep(2);
}
}
int main(int argc,char * argv[])
{
//创建两个线程
pthread_t test1;
pthread_t test2;
pthread_create(&test1,NULL,thread1,NULL);
pthread_create(&test2,NULL,thread2,NULL);
pthread_join(test1,NULL);
pthread_join(test2,NULL);
return 0;
}