|
发表于 2023-10-16 16:17:10
|
显示全部楼层
回帖奖励 +20 鱼币
你好,这个错误是由于缺少 pthread 库导致的。你需要在编译时链接 pthread 库,可以在编译时加上 -lpthread 参数来链接该库。修改代码如下:
- /*
- * @Description: multi-thread sync : read-write lock
- * @Author:
- * @version:
- * @Date: 2023-10-16 10:01:24
- * @LastEditors:
- * @LastEditTime: 2023-10-16 10:31:11
- */
- //==============================================================================
- // Include files
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/types.h>
- #include <unistd.h>
- #include <pthread.h>
- //==============================================================================
- // Constants
- #define MAX_N_WRITE 3
- #define MAX_N_READ 5
- #define MAX(a,b) ((a)>(b) ? (a):(b))
- #define MIN(a,b) ((a)<(b) ? (a):(b))
- //==============================================================================
- // types
- struct RW_DATA_ST
- {
- pthread_rwlock_t rwlock; // 修改此处
- int number;
- };
- //==============================================================================
- // global varibles
- struct RW_DATA_ST g_rw_data;
- //==============================================================================
- // global functions
- void *thread_write(void *arg);
- void *thread_read(void *arg);
- //==============================================================================
- // The main entry-point function.
- int main(int argc, char **argv)
- {
- pthread_rwlock_init(&g_rw_data.rwlock, NULL); // 初始化读写锁
- pthread_t write_tid[MAX_N_WRITE];
- pthread_t read_tid[MAX_N_READ];
- int i = 0;
- for (i = 0; i < MAX_N_WRITE; i++)
- {
- pthread_create(&write_tid[ i], NULL, thread_write, (void*)i);
- }
- for (i = 0; i < MAX_N_READ; i++)
- {
- pthread_create(&read_tid[ i], NULL, thread_read, (void*)i);
- }
- for (i = 0; i < MAX_N_WRITE; i++)
- {
- pthread_join(write_tid[ i], NULL);
- }
- for (i = 0; i < MAX_N_READ; i++)
- {
- pthread_join(read_tid[ i], NULL);
- }
- pthread_rwlock_destroy(&g_rw_data.rwlock); // 销毁读写锁
- exit(0);
- }
- void *thread_write(void *arg)
- {
- int i = 0;
- for (i = 0; i < 10; i++)
- {
- pthread_rwlock_wrlock(&g_rw_data.rwlock); // 获取写锁
- g_rw_data.number = i;
- printf("write thread %d write number %d\n", (int)arg, g_rw_data.number);
- pthread_rwlock_unlock(&g_rw_data.rwlock); // 释放写锁
- sleep(1);
- }
- return (NULL);
- }
- void *thread_read(void *arg)
- {
- int i = 0;
- for (i = 0; i < 10; i++)
- {
- pthread_rwlock_rdlock(&g_rw_data.rwlock); // 获取读锁
- printf("read thread %d read number %d\n", (int)arg, g_rw_data.number);
- pthread_rwlock_unlock(&g_rw_data.rwlock); // 释放读锁
- sleep(1);
- }
- return (NULL);
- }
复制代码
编译时使用以下命令:
- gcc -o test test.c -lpthread
复制代码
注意:请根据实际需求修改代码中的读写锁的初始化和销毁位置。 |
|