在Linux系统中,C++可以通过多种方式实现并发控制。以下是一些常用的方法:
POSIX Threads 是一种标准的线程库,可以在大多数Unix-like系统上使用,包括Linux。
#include <pthread.h>
#include <iostream>
void* thread_function(void* arg) {
std::cout << "Thread is running" << std::endl;
return nullptr;
}
int main() {
pthread_t thread;
int result = pthread_create(&thread, nullptr, thread_function, nullptr);
if (result != 0) {
std::cerr << "Error creating thread" << std::endl;
return 1;
}
pthread_join(thread, nullptr);
std::cout << "Thread finished" << std::endl;
return 0;
}
C++11引入了标准库线程支持,提供了更现代和易用的接口。
#include <thread>
#include <iostream>
void thread_function() {
std::cout << "Thread is running" << std::endl;
}
int main() {
std::thread t(thread_function);
t.join();
std::cout << "Thread finished" << std::endl;
return 0;
}
互斥锁用于保护共享资源,防止多个线程同时访问。
#include <thread>
#include <mutex>
#include <iostream>
std::mutex mtx;
void print_block(int n, char c) {
mtx.lock();
for (int i = 0; i < n; ++i) {
std::cout << c;
}
std::cout << '\n';
mtx.unlock();
}
int main() {
std::thread th1(print_block, 50, '*');
std::thread th2(print_block, 50, '$');
th1.join();
th2.join();
return 0;
}
条件变量用于线程间的同步,允许一个线程等待某个条件成立。
#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_id(int id) {
std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck, []{return ready;});
std::cout << "Thread " << id << '\n';
}
void go() {
std::unique_lock<std::mutex> lck(mtx);
ready = true;
cv.notify_all();
}
int main() {
std::thread threads[10];
for (int i = 0; i < 10; ++i) {
threads[i] = std::thread(print_id, i);
}
std::cout << "10 threads ready to race...\n";
go();
for (auto& th : threads) {
th.join();
}
return 0;
}
信号量是一种更高级的同步机制,可以用于控制对共享资源的访问。
#include <semaphore.h>
#include <pthread.h>
#include <iostream>
sem_t sem;
void* thread_function(void* arg) {
sem_wait(&sem);
std::cout << "Thread is running" << std::endl;
sem_post(&sem);
return nullptr;
}
int main() {
sem_init(&sem, 0, 1); // Initialize semaphore with value 1
pthread_t thread;
pthread_create(&thread, nullptr, thread_function, nullptr);
pthread_join(thread, nullptr);
sem_destroy(&sem);
return 0;
}
读写锁允许多个读取者同时访问共享资源,但写入者独占访问。
#include <shared_mutex>
#include <thread>
#include <iostream>
std::shared_mutex rw_mtx;
void read_function() {
std::shared_lock<std::shared_mutex> lock(rw_mtx);
std::cout << "Reading data\n";
}
void write_function() {
std::unique_lock<std::shared_mutex> lock(rw_mtx);
std::cout << "Writing data\n";
}
int main() {
std::thread readers[5];
std::thread writers[2];
for (int i = 0; i < 5; ++i) {
readers[i] = std::thread(read_function);
}
for (int i = 0; i < 2; ++i) {
writers[i] = std::thread(write_function);
}
for (auto& th : readers) {
th.join();
}
for (auto& th : writers) {
th.join();
}
return 0;
}
这些方法可以根据具体需求选择使用,以实现高效的并发控制。