multithreading - 成对的屏障线程同步
问题描述
我想实现一个阻止传入线程的函数,直到 2 个相同颜色的线程相遇。每个线程都由唯一的 id 和颜色建模。该函数应返回与其匹配的另一个线程的 id。我尝试使用会合和屏障的想法来解决问题,当任何时候只有2个线程时它有效,但是当有2个以上的线程时,返回的id不正确。我试图先解决一种颜色,因为其他两种颜色会有类似的逻辑,但我不确定我需要改变什么?
int pack_thread(int colour, int id) {
if (colour == 1) {
sem_wait(&d); map[0][count[0]] = id; count[0]++;
if (count[0] == 1) {
sem_post(&d);
sem_post(&a1); sem_wait(&a2); sem_post(&barr);
return map[0][1];
} else if (count[0] == 2) {
sem_post(&d);
sem_wait(&a1); sem_post(&a2);
return map[0][0];
} else {
sem_post(&d);
sem_wait(&barr);
map[0][1] = id;
count[0] = 0;
sem_post(&a2);sem_wait(&a1);
return map[0][0];
}
} else {
return 0;
}
解决方案
推荐阅读
- python - 尝试将 CI 添加到 python 项目时出错
- javascript - 使用 Electron 将 Angular 框架应用程序转换为桌面应用程序
- android-sqlite - 在 SQLite Android Studio 中更新单行
- jenkins - 通过 SVN 从 Jenkins 更新工作区时出现间歇性“SVNException: svn: E175002: Connection reset”
- python - Django 多对多字段和表单
- svg - 具有百分比和像素值的响应式 svg
- angular - 在选择菜单中添加所选项目列表
- wso2 - wso2 - 问题逗号合并 API_REQ_USER_BROW_SUMMARY
- html - jQuery 将 css 添加到当前 li js
- java - 从 SFTP url 下载文件