Skip to content

Instantly share code, notes, and snippets.

@tosone
Created October 25, 2020 06:45
Show Gist options
  • Save tosone/606066a4906a246dfa66ef59fb43b838 to your computer and use it in GitHub Desktop.
Save tosone/606066a4906a246dfa66ef59fb43b838 to your computer and use it in GitHub Desktop.
分析其中 data race 问题,并预估输出结果。
#include <adding.h>
void *adding(void *input) {
struct Data *data = (struct Data *)input;
for (int i = 0; i < 1000; i++) {
data->acnt++;
data->cnt++;
}
pthread_exit(NULL);
}
#include <pthread.h>
#include <stdatomic.h>
struct Data {
_Atomic int acnt;
int cnt;
};
void *adding(void *input);
#undef NDEBUG
#include <assert.h>
#include <stdio.h>
#include <adding.h>
int main() {
struct Data data;
pthread_t tid[10];
for (int i = 0; i < 10; i++) {
pthread_create(&tid[i], NULL, adding, (void *)&data);
}
for (int i = 0; i < 10; i++) {
pthread_join(tid[i], NULL);
}
printf("the value of acnt is %d\n", data.acnt);
printf("the value of cnt is %d\n", data.cnt);
assert(data.acnt == 10000);
assert(data.cnt == 10000);
return 0;
}
TARGET = main.test
CFLAGS += -std=c11 -I. -Os -pthread
LDFLAGS +=
CPPFLAGS += -Wall
all: main.o adding.o
$(CC) -o $(TARGET) $? $(LDFLAGS) $(LDLIBS)
test:
./$(TARGET)
clean:
$(RM) *.o *.test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment