我刚开始使用 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, ¶m);
thrd_join(t, NULL);
}
自 TinyCThread是TinyThread++的C替代品, 你应该使用那个 C++ 类库。
此外,C++ 支持 std::thread
看看吧。
关于c++ - 如何使用tinycthread做C++并发编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19594061/