Created
October 25, 2020 06:45
-
-
Save tosone/606066a4906a246dfa66ef59fb43b838 to your computer and use it in GitHub Desktop.
分析其中 data race 问题,并预估输出结果。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pthread.h> | |
#include <stdatomic.h> | |
struct Data { | |
_Atomic int acnt; | |
int cnt; | |
}; | |
void *adding(void *input); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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