linux下锁的使用
代码:
#include <iostream> #include <pthread.h> #include <unistd.h> class Mutex { public: Mutex() { //设置递归属性 pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP); pthread_mutex_init(&m_locker, &attr); pthread_mutexattr_destroy(&attr); } ~Mutex() { pthread_mutex_destroy(&m_locker); } //加锁 bool Lock(bool block = true) { if (block) { pthread_mutex_lock(&m_locker); return true; } return (pthread_mutex_trylock(&m_locker) == 0); } //加锁 bool Trylock() { return (pthread_mutex_trylock(&m_locker) == 0); } //解锁 void Unlock() { pthread_mutex_unlock(&m_locker); } private: pthread_mutex_t m_locker; }; Mutex locker; int jiu = 0; //读操作 void *rthread (void *t) { while (true) { locker.Lock(); printf("hello read!\n"); if (jiu) { printf ("read\n"); jiu = 0; } locker.Unlock(); sleep(1); } } //写操作 void *wthread (void *t) { while (true) { locker.Lock(); printf("hello write!\n"); if (!jiu) { printf ("write\n"); jiu = 1; } locker.Unlock(); sleep(1); } } int main () { pthread_t id; long t = 0x123; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);//分离式线程 pthread_create(&id, &attr, rthread, (void *)t); pthread_create(&id, &attr, wthread, (void *)t); sleep(60); return 0; }
上面代码,大意是实现一个临界资源的读写操作,写与读不能冲突。线程创建部分,可参看Linux下的多线程编程
配置make编译文件:
创建src文件夹,将cpp文件放该文件夹下。在src文件夹同级目录下创建CMakeLists.txt文件,内容为:
cmake_minimum_required(VERSION 2.8) PROJECT(thread) SET(CMAKE_CXX_FLAGS "-DDEBUG -Wno-invalid-offsetof -Wno-deprecated -gdwarf-2 -g3 -std=c++0x -g") AUX_SOURCE_DIRECTORY(src DIR_SRCS) SET(THREAD ${DIR_SRCS}) ADD_EXECUTABLE(./bin ${THREAD}) TARGET_LINK_LIBRARIES(./bin pthread)
在终端,执行命令:
cmake .
make -j
也可以使用make -jn命令,其中n为cpu的核数。