我试图使用p_thread按顺序打印数字:0123.4没有使用全局变量,只是局部变量,但我遇到了死锁,我不知道如何修复它。这是我的代码:
#include <pthread.h>
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
static pthread_mutex_t bsem; // Mutex semaphore
static pthread_cond_t waitTurn = PTHREAD_COND_INITIALIZER; // Condition variable to control the turn
//static int turn; // Index to control access to the turn array
static int nthreads; // Number of threads from input
struct SFE{
int turn;
int thread;
};
void *thread_function(void *void_ptr_argv)
{
SFE *threadNum = (SFE *) void_ptr_argv;
pthread_mutex_lock(&bsem);
// if its not our turn then wait
while(threadNum->turn != threadNum->thread){
pthread_cond_wait(&waitTurn, &bsem);
}
pthread_mutex_unlock(&bsem);
std::cout << "I am Thread " << threadNum->turn << std::endl;
pthread_mutex_lock(&bsem);
threadNum->turn++;
pthread_cond_broadcast(&waitTurn);
pthread_mutex_unlock(&bsem);
return nullptr;
}
int main()
{
std::cin >> nthreads;
pthread_mutex_init(&bsem, NULL); // Initialize bsem to 1
pthread_t *tid= new pthread_t[nthreads];
SFE threadNumber;
threadNumber.turn = 0;
for(int i=0;i<nthreads;i++)
{
// initialize the thread number here (remember to follow the rules from the specifications of the assignment)
threadNumber.thread = i;
pthread_create(&tid[i], nullptr, thread_function, (void*)&threadNumber);
}
for(int i = 0; i < nthreads; i++)
{
pthread_join(tid[i], nullptr);
}
return 0;
}
我希望有一个简单的方法来解决我的问题
想想threadNum->thread
。threadNum
是一个唯一的对象,因此每个线程获得一个未指定的数字threadNum->thread
,在0到nthreads
之间。只有最后一个线程得到正确的数字nthreads - 1
。
你应该更新
struct SFE{
int *turn;
int thread;
};
分配数组SFE threadNum[nthread]
并将&threadNum[i]
传递给第i个线程。
int turn = 0;
for(int i=0;i<nthreads;i++)
{
// initialize the thread number here (remember to follow the rules from the specifications of the assignment)
threadNumber[i].turn = &turn;
threadNumber[i].thread = i;
pthread_create(&tid[i], nullptr, thread_function, &threadNumber[i]);
}
你的代码是C-ism。这段没有iostream和new
的代码是一个干净的C。如果你使用c++,一切都会容易得多。