任务资源互斥编程可以通过多种方法实现,以下是几种常见的方法:
1. 使用互斥锁(Mutex)
互斥锁是一种同步机制,用于防止多个线程同时访问共享资源。以下是一个使用POSIX互斥锁的示例:
```c
include include pthread_mutex_t work_mutex; // 声明互斥量 char Share; // 共享资源区 void* My_thread_1(void* args) { while(1) { pthread_mutex_lock(&work_mutex); // 加锁 for(int i = 0; i < 9; i++) { Share[i] = 'a'; // 线程1将Share写成aaaaaaaa } Share = '\0'; // 确保字符串以空字符结尾 printf("1 Share is: %s\n", Share); pthread_mutex_unlock(&work_mutex); // 解锁 Sleep(100); // 启用互斥量时也去除注释,为进程调度提供时间 } return NULL; } void* My_thread_2(void* args) { while(1) { pthread_mutex_lock(&work_mutex); // 加锁 for(int i = 0; i < 9; i++) { Share[i] = 'b'; // 线程2将Share写成bbbbbbbb } Share = '\0'; // 确保字符串以空字符结尾 printf("2 Share is: %s\n", Share); pthread_mutex_unlock(&work_mutex); // 解锁 Sleep(100); // 启用互斥量时也去除注释,为进程调度提供时间 } return NULL; } int main() { pthread_t t1, t2; pthread_mutex_init(&work_mutex, NULL); // 初始化互斥锁 pthread_create(&t1, NULL, My_thread_1, NULL); pthread_create(&t2, NULL, My_thread_2, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); pthread_mutex_destroy(&work_mutex); // 销毁互斥锁 return 0; } ``` 2. 使用C++标准库中的`std::mutex` 如果你使用C++,可以使用标准库中的`std::mutex`来实现互斥访问: ```cpp include include include std::mutex mtx; int shared_data = 0; void incrementSharedData() { std::lock_guard shared_data++; std::cout << "Thread " << std::this_thread::get_id() << " incremented shared_data to " << shared_data << std::endl; } int main() { std::thread t1(incrementSharedData); std::thread t2(incrementSharedData); t1.join(); t2.join(); return 0; } ``` 3. 使用Windows API 在Windows平台上,可以使用`CRITICAL_SECTION`、`HANDLE`(用于`CreateMutex`和`CreateSemaphore`)来实现互斥访问: