多线程交换2个预定义指针到1个静态指针线程安全吗?

min*_*oon 2 c c++ multithreading assignment-operator

我已经参考了这个链接 - > https://gist.github.com/Taymindis/3938e917aaae4fc480386f494be62f0e并做了一些valgrind检查,它没有错误.但我只想双重确认以下这个例子考虑线程安全吗?

我个人阴道检查,它没有错误,有没有人有更好的主意?

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>

#define THREAD_RUN 100

static char *global;

static char *x1 = "This is thread 1";

static char *x2 = "This is thread 2";

void * write(void* thr_data) {
    int n = *(int*)thr_data;

    if(n%2==0) goto RETRY1;
    else goto RETRY2;

RETRY1:
    for (n = 0; n < 1000; ++n) {
        global = x1;
    }
    goto RETRY1;


RETRY2:
    for (n = 0; n < 1000; ++n) {
        global = x2;
    }
    goto RETRY2;

    // free(cu);
    return 0;
}

void * read(void* thr_data)
{
    int n;
RETRY:
    for (n = 0; n < 1000; ++n) {
        if(global[0] == 'C');
    }
    goto RETRY;
    return 0;
}


int main(void)
{
    int n;
    pthread_t read_thr[THREAD_RUN];
    pthread_t write_thr[THREAD_RUN];

    global = x1;

    for (n = 0; n < THREAD_RUN; ++n) {
        pthread_create(&write_thr[n], NULL, write, &n);
        pthread_create(&read_thr[n], NULL, read, &n);
    }

    for (n = 0; n < THREAD_RUN; ++n)
        pthread_join(read_thr[n], NULL);

    for (n = 0; n < THREAD_RUN; ++n)
        pthread_join(write_thr[n], NULL);

} 
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 6

不,C或C++无法保证指针赋值是原子的.

(例如,完全可以想象一个指针跨越两个寄存器,最后你会混淆x1x2).

您的代码不是线程安全的.

  • 这不是唯一的问题.因为变量既不是原子也不是volatile,编译器可能会进行任何选择的优化,包括只在每个线程中写入一次然后进入无限的无操作循环. (2认同)