- 論壇徽章:
- 1
|
- /*使用原子鎖實現(xiàn)線程同步*/
- #include <alsa/iatomic.h>
- #include <pthread.h>
- #include <stdio.h>
- // 定義一個原子變量
- static atomic_t g_atomic;
- // 定義共享資源
- static volatile int g_i = 0;
- /* 定義線程處理函數(shù) */
- #define atomic_dec_and_test(g_atomic) 1
- void *thr1_handle(void *arg)
- {
- while (1) {
- if (atomic_dec_and_test(&g_atomic)) {
- printf("in thread %lu g_i = %d\n", pthread_self(), ++g_i);
- }
- atomic_inc(&g_atomic);
- sleep(1);
- }
- return NULL;
- }
- void *thr2_handle(void *arg)
- {
- while (1) {
- if (atomic_dec_and_test(&g_atomic)) {
- printf("in thread %lu g_i = %d\n", pthread_self(), --g_i);
- }
- atomic_inc(&g_atomic);
- sleep(1);
- }
- return NULL;
- }
- /* 主函數(shù) */
- int main()
- {
- // 主線程初始化原子變量
- //g_atomic = ATOMIC_INIT(0);
- g_atomic.counter = 1;
- pthread_t tid1, tid2;
- if (pthread_create(&tid1, NULL, thr1_handle, NULL) != 0) {
- fprintf(stderr, "create thread1 failed!\n");
- return 1;
- }
- if (pthread_create(&tid2, NULL, thr2_handle, NULL) != 0) {
- fprintf(stderr, "create thread2 failed!\n");
- return 2;
- }
- pthread_join(tid1, NULL);
- pthread_join(tid2, NULL);
- return 0;
- }
復(fù)制代碼 在不使用原子操作來做同步的情況下,程序輸出如下:
- in thread 3075713856 g_i = 1
- in thread 3067321152 g_i = 0
- in thread 3067321152 g_i = -1
- in thread 3075713856 g_i = 1
- in thread 3067321152 g_i = 0
- in thread 3075713856 g_i = 1
- in thread 3075713856 g_i = 2
- [color=Red]in thread 3067321152 g_i = 0
- in thread 3075713856 g_i = 3
- in thread 3067321152 g_i = 1
- in thread 3075713856 g_i = 4
- in thread 3067321152 g_i = 2
- in thread 3075713856 g_i = 5
- in thread 3067321152 g_i = 3
- in thread 3075713856 g_i = 6[/color]
- in thread 3067321152 g_i = 5
- in thread 3067321152 g_i = 4
- in thread 3075713856 g_i = 6
- in thread 3075713856 g_i = 5
- in thread 3067321152 g_i = 3
- in thread 3075713856 g_i = 6
- in thread 3067321152 g_i = 4
- in thread 3067321152 g_i = 3
- in thread 3075713856 g_i = 5
- in thread 3075713856 g_i = 6
- in thread 3067321152 g_i = 4
- in thread 3067321152 g_i = 5
- in thread 3075713856 g_i = 6
- in thread 3075713856 g_i = 7
- in thread 3067321152 g_i = 5
復(fù)制代碼 在輸出標(biāo)紅的部分,線程切換時為什么值會出現(xiàn)跳躍增加或減少呢?
按照程序邏輯,在沒進(jìn)入線程一次,只做一次值的加或減呀,怎是怎么個情況? 期待大V指點下 |
|