【发布时间】:2018-08-16 10:27:28
【问题描述】:
这似乎是一个基本问题,但请耐心等待。
我需要开发一个多线程程序,它有许多线程等待主线程分配它们工作(类似于生产者消费者线程)。我有条件变量来提醒线程停止等待并开始工作,然后返回等待状态。我在条件变量上有一个互斥锁,它将被锁定并在主线程的控制下。我在工作线程上调用函数 def()。
主线程
int def(int y)
{
// Signal the worker threads to stop waiting and start working
pthread_cond_signal(&condvar);
pthread_mutex_lock(&mutex);
pthread_cond_wait(&condvar1, &mutex);
pthread_mutex_unlock(&mutex);
fprintf(stderr, "\nInside the thread");
return 0;
}
int init()
{
// Initialize the thread condition variables
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&condvar, NULL);
pthread_cond_init(&condvar1, NULL);
int x=0;
if(pthread_create(&mythread, NULL, abc, &x)) {
fprintf(stderr, "Error creating thread\n");
}
return 0;
}
我的问题是程序对时间敏感,锁定指令需要几千纳秒。
我的问题是,我可以在不使用互斥锁的情况下与线程交互并让它们等待吗?我有独立的工作线程,它们不访问彼此的数据。主线程和工作线程相互传递数据。
正确的方法是什么?
【问题讨论】:
-
除了互斥锁和条件变量之外,您还尝试过什么?您可以使用信号量。您可以使用pipe 作为分配工作的队列(将指针值写入管道,工作线程从管道中读取指针值)。您可以尝试无锁队列(而那些tend not to work very well,也许他们会为您工作)。没有“正确的方法”。
标签: c multithreading locking mutex