检查线程是否未使用 C

标签 c multithreading

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

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_tpthread_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?

关于检查线程是否未使用 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21390325/

相关文章:

c++ - C/C++ 中字符的大小 ('a' )

c# - 通过同一 session 进行 Telegram 客户端更新和 API 请求

c - 让 Qt 调试器工作 (GDB)

c - 将 char 数组拆分为单独的字符串

c - 为什么我无法使用 Visual Studio 2015 RC 命令行工具构建 Vim?

android - 在android上将openGL渲染与c++游戏循环同步

java - 中断Java中的循环线程

java - ThreadPoolExecutor$Worker 中的奇怪代码

c - FD_SET、FD_CLR ...是原子操作吗?

c - 同时在一个流中使用 fread 和 fwrite 会导致问题