r*******a 发帖数: 7 | 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);
} |
a******7 发帖数: 106 | |
r*******a 发帖数: 7 | 3 Mutex needs to put thread on sleep (no busy waiting), how do I block the
thread and wake them up?
【在 a******7 的大作中提到】 : http://en.cppreference.com/w/c/atomic/atomic_compare_exchange
|
a******7 发帖数: 106 | 4 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 |
r*******a 发帖数: 7 | 5 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
|
a******7 发帖数: 106 | 6 哦 我明白你的意思了 我不熟pthread 但这样行吗
condition_variable cv;
void lock() {
while (flag == 1) cv.wait();
flag = 1;
}
void unlock() {
flag = 0;
cv.notify_all();
} |
c*********i 发帖数: 36 | 7 马上onsite了,求好心人解答,如何没有busy waiting |