on-internet
← Community

Why does multi-thread program still need lock when running on a single-core CPU? [duplicate]

Stack Overflow ·

After reading Why memory reordering is not a problem on single core/processor machines?, I wrote a small multi-thread program which runs on a single-core CPU: #include <pthread.h> #include <stdio.h> #include <stdint.h> #include <inttypes.h> #include <string.h> #define THREAD_NUM 4 #define SUM_LOOP_SIZE 100000 uint64_t sum; void * thread(void *arg) { for (int i = 0; i < SUM_LOOP_SIZE; i++) { sum++; } return NULL; } int main() { pthread_t tid[THREAD_NUM]; uint64_t counter = 0; while (1) { counter++; for (int i = 0; i < THREAD_NUM; i++) { int ret = pthread_create(&tid[i], NULL, thread, NULL); if

Comments

Sign in or sign up to comment and upvote.

No comments yet.