C/C++多线程与互斥锁
void * thread (void *id) {
printf ("this is a new thread, thread ID is %u\n" , pthread_self());
return NULL ;
}
#include <unistd.h>
#include <sys/syscall.h>
#define gettid() syscall(__NR_gettid)
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL );
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
pthread_mutex_lock(mutex);
while (条件不成立)
{
pthread_cond_wait(cond, mutex);
}
...
pthread_mutex_unlock(mutex);
pthread_cond_signal(pthread_cond_t * cond);
pthread_cond_broadcast(pthread_cond_t * cond);
pthread_cond_timedwait(pthread_cond_t * cond, pthread_mutex_t * mutex, struct timespec * time);
条件锁与互斥锁应用:
pthread_mutex_lock(&m_mutex);
pthread_cond_wait(&m_cond,&m_mutex);
pthread_mutex_unlock(&m_mutex);
pthread_mutex_lock(&m_mutex);
pthread_cond_signal(&m_cond);
pthread_mutex_unlock(&m_mutex);
spin_lock_init(spinlock_t *x);
spin_lock(x);
spin_trylock(x);
spin_unlock(x);
spin_is_locked(x);
pthread_rwlock_t rwlock;
int data=1 ;
void readerA () {
while (1 ){
pthread_rwlock_rdlock(&rwlock);
printf ("A读者读出:%d\n" ,data);
pthread_rwlock_unlock(&rwlock);
Sleep(1000 );
}
}
void writerB () {
while (1 ){
pthread_rwlock_wrlock(&rwlock);
data++;
printf ("B作者写入:%d\n" ,data);
pthread_rwlock_unlock(&rwlock);
Sleep(1000 );
}
}
int main ()
{
pthread_t t1;
pthread_t t2;
pthread_rwlock_init(&rwlock,NULL );
pthread_create(&t1,NULL ,readerA,NULL );
pthread_create(&t2,NULL ,writerB,NULL );
pthread_join(t1,NULL );
pthread_join(t2,NULL );
pthread_rwlock_destroy(&rwlock);
return 0 ;
}
C++多线程互斥锁:
#include <thread>
#include <mutex>
#include <iostream>
int g_i = 0 ;
std ::mutex g_i_mutex;
void safe_increment ()
{
std ::lock_guard<std ::mutex> lock (g_i_mutex) ;
++g_i;
std ::cout << std ::this_thread::get_id() << ": " << g_i << '\n' ;
}
int main ()
{
std ::cout << "main: " << g_i << '\n' ;
std ::thread t1 (safe_increment) ;
std ::thread t2 (safe_increment) ;
t1.join();
t2.join();
std ::cout << "main: " << g_i << '\n' ;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具