【问题标题】:Writing and reading from a buffer with pthread使用 pthread 从缓冲区写入和读取
【发布时间】:2019-02-28 16:02:37
【问题描述】:

我正在尝试使用 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);
}

【问题讨论】:

  • 线程如何等待你填满数组?它在填充数组之前运行。它们同时运行。使用 pthread_barrier 或 pthread_mutex 来同步它们。
  • 我希望他们同时工作。这就是我在填充数组之前创建线程的原因。换句话说,我希望在填充了 100 个数组元素后激活线程。 pthread 创建后是否开始工作? @KamilCuk
  • "pthread 创建后是否开始工作?" 迟早是的。
  • 但是你的线程需要等待数组被填充。它没有。它只是检查并存在。然后你开始在你的主线程中填充数组。创建一个已锁定的 pthread_mutex,并在将 args.arg1 增加到 100 后将其解锁。您可以在循环中检查 args.arg1,但它可能不起作用,并且 args.arg1 必须是原子的。
  • 您可能想看看互斥锁和条件。

标签: c linux pthreads pthread-join pthread-barriers


【解决方案1】:

线程在您进入 for 循环时终止。 arg1 仍未在 ProcessThread 中初始化。您可以使用带有 sleep 功能的 while 循环来定期测试条件。

【讨论】:

    猜你喜欢
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    相关资源
    最近更新 更多