Skip to content

pthread_spin_unlock 的实现不正确 #10

Closed
@ganlvtech

Description

@ganlvtech

static inline int pthread_spin_unlock(pthread_spinlock_t *lock) {
__asm__ __volatile__ ("" ::: "memory");
*lock = 0;
return 0;
}

https://stackoverflow.com/questions/12183311/difference-in-mfence-and-asm-volatile-memory

asm volatile ("" ::: "memory") 编译之后反编译看没有生成任何指令,它只是告诉编译器不要做指令重排吧

static inline int pthread_spin_unlock(pthread_spinlock_t *lock) {
	__sync_sub_and_fetch(lock, 1);
	return 0;
}

__sync_synchronize() 也可以,它会生成一个 ARM 的 __dmb(11) 的操作
不用的话就是啥也不管。

测试代码也做了一定的修改

void *thread_proc(void *arg) {
    int thread_id = (int) (intptr_t) arg;
    MY_INFO("thread %d start", thread_id);
    for (int i = 0; i < LOOP_COUNT; i++) {
        PthreadWriteGuard guard(g_test_mutex);
        if (a != b || b != c || c != d) {
            MY_ERROR("pthread unit test failed: thread %d: %d %d %d %d", thread_id, a, b, c, d);
        }
        a++;
        b++;
        c++;
        d++;
    }
    MY_INFO("thread %d stop", thread_id);
    pthread_exit(0);
    return 0;
}

可以测出 asm volatile__sync_sub_and_fetch 的差别

test_mutex

我可以提交一个 Pull Request

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions