c++ - 如何使用tinycthread做C++并发编程

标签 c++ multithreading tinycthread

我刚开始使用 tinycthread.h 进行并发编程。但是,我不知道如何使用它。目前,我想知道如何使用该库创建线程函数。

这里是tinycthread库中列出的两个函数

typedef int(* thrd_start_t)(void *arg)
int thrd_create (thrd_t * thr,thrd_start_t func,void * arg )        

我想创建一个以整数作为参数的线程函数。

int Haha (int a){} ->  to be my thread function

int main(){
thrd_t t;
thrd_create(&t,Haha,int a);

}

我在我的程序中写了这样的东西。

但作为接受的 typedef int(* thrd_start_t)(void *arg) typedef 是这样的,它不允许我将任何整数作为我的参数。那么我应该怎么做才能创建一个以整数作为参数的线程函数。

最佳答案

Haha 的参数必须是 void * 而不是 int,因此请尝试通过一些转换来传递您的整数输入:

int Haha (void *arg)
{
    int *a = static_cast<int*>(arg);

    printf("%d", *a);
    return 0;
}

int main()
{
    int param = 123;

    thrd_t t;
    thrd_create(&t, Haha, &param);
    thrd_join(t, NULL);
}

TinyCThreadTinyThread++的C替代品, 你应该使用那个 C++ 类库。

此外,C++ 支持 std::thread看看吧。

关于c++ - 如何使用tinycthread做C++并发编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19594061/

相关文章:

c++ - 跨线程函数调用修改变量

Java 8 非阻塞读取有竞争条件?

c++ - tinycthread编译错误

c++ - glGenBuffers 没有定义?

c++ - 用异构 boost::fusion vector 类型数据填充 std::vector

c++ - 不使用静态变量的原因?

c++ - 移除和删除 vector 中的所有对象

c++ - 使用线程在python中调用多个c++函数