线程之间的通信方式有哪些?(附代码帮助理解)

通信方式优点缺点
共享变量实现简单,性能较好需要同步机制防止数据竞争,可能导致死锁
条件变量用于线程间同步,可以等待特定条件成立需要结合锁使用,管理复杂
读写锁允许更高的并行性,读写分离管理相对复杂,不当使用可能导致死锁
信号量控制资源访问计数,适用于资源共享不当使用可能导致死锁,需要仔细管理
屏障确保之前的操作对所有线程可见,用于同步单独使用时作用有限,通常与其他同步机制配合使用
消息传递解耦合通信双方,支持异步通信增加系统复杂性,需要处理消息传递和同步问题
1.共享变量
#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx;
int sharedData = 0;

void threadFunction() {
    for (int i = 0; i < 10; ++i) {
        std::lock_guard<std::mutex> lock(mtx);
        ++sharedData;
        std::cout << "Thread " << std::this_thread::get_id() << " incremented shared data to " << sharedData << std::endl;
    }
}

int main() {
    std::thread t1(threadFunction), t2(threadFunction);
    t1.join();
    t2.join();
    return 0;
}
2.条件变量
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mtx;
std::condition_variable cv;
int ready = 0;

void print_id(int id) {
    std::unique_lock<std::mutex> lk(mtx);
    cv.wait(lk, []{ return ready == id; });
    std::cout << "Thread " << id << '\n';
    ++ready;
    cv.notify_one();
}

void wait_for_others() {
    std::unique_lock<std::mutex> lk(mtx);
    cv.wait(lk, []{ return ready == 2; });
}

int main() {
    std::thread t1(print_id, 1), t2(print_id, 2), t3(wait_for_others);
    t1.join();
    t2.join();
    t3.join();
    return 0;
}

3.读写锁

#include <iostream>
#include <thread>
#include <mutex>
#include <shared_mutex>

std::shared_mutex rw_mtx;
int data = 0;

void reader() {
    std::shared_lock<std::shared_mutex> lock(rw_mtx);
    std::cout << "Reader " << std::this_thread::get_id() << " reading data: " << data << '\n';
}

void writer() {
    std::unique_lock<std::shared_mutex> lock(rw_mtx);
    data += 1;
    std::cout << "Writer " << std::this_thread::get_id() << " writing data: " << data << '\n';
}

int main() {
    std::thread threads[10];
    for (int i = 0; i < 10; ++i) {
        threads[i] = i % 2 ? writer : reader;
        threads[i].detach();
    }
    for (auto& th : threads) {
        th.join();
    }
    return 0;
}
4.信号量
#include <iostream>
#include <thread>
#include <semaphore>

std::semaphore s(0);

void worker() {
    s.acquire();
    std::cout << "Worker started.\n";
    // Perform work...
    s.release();
}

int main() {
    std::thread t(worker);
    t.join();
    return 0;
}
5.屏障
#include <iostream>
#include <thread>
#include <barrier>

std::barrier b(2);

void task() {
    // Perform some work...
    b.wait(); // Wait until all threads have reached the barrier.
    // Perform more work that requires synchronization.
}

int main() {
    std::thread t1(task), t2(task);
    t1.join();
    t2.join();
    return 0;
}
6.消息传递
#include <iostream>
#include <string>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>

std::queue<std::string> msg_queue;
std::mutex q_mutex;
std::condition_variable cv;

void producer() {
    for (int i = 0; i < 10; ++i) {
        std::string msg = "Message " + std::to_string(i);
        std::lock_guard<std::mutex> lock(q_mutex);
        msg_queue.push(msg);
        cv.notify_one();
    }
}

void consumer() {
    while (true) {
        std::unique_lock<std::mutex> lock(q_mutex);
        cv.wait(lock, []{ return !msg_queue.empty(); });
        std::string msg = msg_queue.front();
        msg_queue.pop();
        lock.unlock();
        std::cout << "Consumer received: " << msg << '\n';
    }
}

int main() {
    std::thread prod(producer), cons(consumer);
    prod.join();
    cons.join();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值