相关疑难解决方法(0)

C++ 11使用<atomic>实现Spinlock

我实现了SpinLock类,如下所示

struct Node {
    int number;
    std::atomic_bool latch;

    void add() {
        lock();
        number++;
        unlock();
    }
    void lock() {
        bool unlatched = false;
        while(!latch.compare_exchange_weak(unlatched, true, std::memory_order_acquire));
    }
    void unlock() {
        latch.store(false , std::memory_order_release);
    }
};
Run Code Online (Sandbox Code Playgroud)

我实现了上面的类,并创建了两个线程,每个线程调用一个相同的Node类实例的add()方法1000万次.

不幸的是,结果不是2000万.我在这里错过了什么?

c++ multithreading c++11

30
推荐指数
2
解决办法
3万
查看次数

C&低级信号量实现

我正在考虑如何使用尽可能少的asm代码实现信号量(不是二进制).
我没有成功地在没有使用互斥锁的情况下思考和编写它,所以这是迄今为止我能做的最好的事情:

全球:

#include <stdlib.h>
#include <pthread.h>
#include <stdatomic.h>
#include <stdbool.h>

typedef struct
{
    atomic_ullong    value;
    pthread_mutex_t *lock_op;
    bool             ready;
} semaphore_t;

typedef struct
{
    atomic_ullong   value;
    pthread_mutex_t lock_op;
    bool            ready;
} static_semaphore_t;

 /* use with static_semaphore_t */
#define SEMAPHORE_INITIALIZER(value) = {value, PTHREAD_MUTEX_INITIALIZER, true}
Run Code Online (Sandbox Code Playgroud)


功能:

bool semaphore_init(semaphore_t *semaphore, unsigned long long init_value)
{   
    if(semaphore->ready) if(!(semaphore->lock_op = \
                             calloc(1, sizeof(pthread_mutex_t)))) return false;
    else                 pthread_mutex_destroy(semaphore->lock_op);   

    if(pthread_mutex_init(semaphore->lock_op, NULL))
            return false;

    semaphore->value = init_value;
    semaphore->ready = true;
    return true;
}

bool semaphore_wait(semaphore_t *semaphore)
{ …
Run Code Online (Sandbox Code Playgroud)

c assembly multithreading mutex semaphore

6
推荐指数
1
解决办法
2159
查看次数

标签 统计

multithreading ×2

assembly ×1

c ×1

c++ ×1

c++11 ×1

mutex ×1

semaphore ×1