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)
不,C或C++无法保证指针赋值是原子的.
(例如,完全可以想象一个指针跨越两个寄存器,最后你会混淆x1和x2).
您的代码不是线程安全的.
| 归档时间: |
|
| 查看次数: |
174 次 |
| 最近记录: |