【问题标题】:Checking if a thread is unused C检查线程是否未使用 C
【发布时间】:2014-02-18 20:24:25
【问题描述】:

我正在尝试检查数组中的线程是否未使用,然后返回未使用的数组空间

int Check(){
    int a;
    for (a=0;a<12;a++){
        if(tid[a]==0){
            return a;
        }
    }
    return -1;

tid 是一个全局变量

pthread_t tid[12];

我总是得到-1返回,我不知道如何检查线程是否被使用。

我不知道未使用的 pthread_t 等于什么。

这就是我初始化数组的方式:

user[i] = (struct users){i,0,count}; 
pthread_create(&tid[count], NULL, (void*)Actions, &user[i]);

【问题讨论】:

  • 你是如何初始化你的数组元素的?
  • 您为什么希望 pthread_t 永远等于 0?
  • 我不知道未使用的 pthread_t 等于什么
  • user[i] = (struct users){i,0,count}; pthread_create(&tid[count], NULL, (void*)Actions, &user[i]);
  • 请编辑您的问题,而不是在 cmets 上发布。

标签: c multithreading


【解决方案1】:

您无法像您一样仅通过将pthread_t 与常量进行比较来跟踪是否正在使用它。 pthread_t 数据类型的内容故意不向程序员公开。

考虑将您的数组声明为以下结构的数组:

typedef struct {
    bool avaiable;
    pthread_t thread;
} threadrec_t;

使用threadrec_t.avaiable 字段来识别线程是否在使用中。您必须记住在使用它时将其值设置为true,并在工作完成时将其值设置为false

看看这个有什么相关的问题:

How do you query a pthread to see if it is still running?

【讨论】:

    【解决方案2】:

    建议:

    在主线程中,调用pthread_self并在某处捕获返回值;也许是一个全局变量。

    当主线程存活时,任何其他线程的ID不能等于主线程的ID;所以你可以使用这个主线程 ID 作为一个特殊的值来表示“这里没有线程”。

    /* ... */
    
    no_thread = pthread_self(); /* in main */
    
    /* ... */
    
    if (pthread_create(&tid[i], ...)) {
      /* failed */
      tid[i] = no_thread;
    }
    
    /* ... */
    if (pthread_equal(tid[i], no_thread)) {
      /* no thread at index i */
    }
    

    另一种方法是有一个并行数组tid_valid[] 的布尔值,表示存在对应的tid 值的有效性。或者像这样的结构:

    struct thread_info {
      pthread_t id;
      int valid;
    };
    

    并制作这些结构的tid 数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-16
      • 1970-01-01
      相关资源
      最近更新 更多