Redian新闻
>
FREE Sample of Disney Character Vitamin Gummies
avatar
FREE Sample of Disney Character Vitamin Gummies# PennySaver - 省钱一族
r*a
1
我想用conditional variable, 可是pthread_cond_wait() only take mutex. 难道要
自己写cv_wait() 和cv_signal?
我的思路:
typedef struct mutex {
pthread_spin_lock_t lock;
int flag;
} mutex_t;
void mutex_lock(mutex_t *m)
{
pthread_spin_lock(&m->lock);
while (flag == 1)
cv_wait(flag, &m->lock); // I don't know which cv_wait to use that will
take spin lock
flag = 1;
pthread_spin_unlock(&m->lock);
}
void mutex_unlock(mutex_t *m)
{
pthread_spin_lock(&m->lock);
flag = 0;
cv_signal(flag);
pthread_spin_unlock(&m->lock);
}
avatar
s*y
4
3x
avatar
m*r
6
thx
avatar
c*r
8
thanks!
avatar
r*a
9
Sorry that I can't type chinese.
The difference between spin lock and mutex is that spin lock will do busy
wait and hog the cpu, but mutex wont. Using this atomic flag, the thread
will be still busy waiting.

【在 a******7 的大作中提到】
: atomic flag(0);
: void lock() {
: while (flag.compare_exchange_strong(0, 1));
: }
: void unlock() {
: flag = 0;
: }
: 其实bool就够了
: http://en.cppreference.com/w/cpp/atomic/atomic_flag

avatar
b*g
10
thx!
avatar
a*7
11
哦 我明白你的意思了 我不熟pthread 但这样行吗
condition_variable cv;
void lock() {
while (flag == 1) cv.wait();
flag = 1;
}
void unlock() {
flag = 0;
cv.notify_all();
}
avatar
c*i
13
马上onsite了,求好心人解答,如何没有busy waiting
avatar
g*e
14
Thx
avatar
p*g
15
3x
avatar
o*y
16
3x
avatar
y*w
17
thanks
avatar
b*y
18
3x
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。