c - 使用 pthread 从缓冲区写入和读取
问题描述
我正在尝试使用 pthread。在下面的代码中,我定义了两个全局变量(arg1 和 arg2),在主函数中,我开始用 1 填充 arg2 的每个元素。我希望 pthread 在 arg2 的第 101 个元素被填充后立即打印它主要的。但是 pthread 什么也没打印。实际上 arg1 的变化并没有跟随 pthread 并且 pthread 假设 arg1 为 0。如何激活 pthread 以便当我在 main 中写入缓冲区时,pthread 同时开始从缓冲区读取?
提前致谢。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <math.h>
#include <sys/time.h>
#include <unistd.h>
#include <assert.h>
#include <signal.h>
#include <pthread.h>
struct arg_struct {
int arg1;
int arg2[1000];
};
//volatile int arg1;
//int arg2[1000];
void *ProcessThread (void *arguments){
struct arg_struct *args = arguments;
if( args -> arg1==100) {
printf("%d", args -> arg2[ args -> arg1]);
}
pthread_exit(NULL);
return NULL;
}
void main(){
struct arg_struct args;
pthread_t thread1;
void *thread_status;
pthread_create(&thread1, NULL, ProcessThread, (void *)&args);
for ( args.arg1=0; args.arg1<1000; args.arg1++){
args.arg2[args.arg1] =1;
}
pthread_join(thread1,&thread_status);
}
解决方案
当您进入 for 循环时,线程将终止。arg1
中仍未初始化ProcessThread
。您可以使用带有 sleep 功能的 while 循环来定期测试条件。
推荐阅读
- javascript - 每次Angular发生更改时如何更新现有组件?
- html - 我如何使侧边菜单在默认情况下为宽 pc 分辨率打开
- spring-security - Spring Security 5.2.2 + Spring Boot 2.2 + Oauth 自动配置:允许一些 uri 并且只保护少数几个:403 错误
- powershell - 在配置文件 powershell 或批处理文件中查找和替换
- android - LibVLC Android:安装指南?
- shell - 如何使用基本终端导航命令使符号出现在单词列表中的几个特定位置?
- c# - 通过视图编辑数据库行仅导致 2/3 值的空值
- vim - 如何使这个vim文件浏览器功能在neovim中工作?
- node.js - exceljs读取一个单元格而不是解析为等待页面。$ eval
- java - wireshark 可以抓到tcp 包,但是我的socket 收不到数据