我正在编写一个代码,它创建10个线程并首先使用偶数线程ID执行这些线程,然后执行所有具有奇数线程ID的线程。我正在使用POSIX线程库。这是我写的代码:
#include "stdlib.h"
#include "pthread.h"
#include "stdio.h"
#define TRUE 1
#define FALSE 0
int EVEN_DONE = FALSE;
int evenThreads, oddThreads = 0;
int currentThread = 0;
//the mutex for thread synchronization
static pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
//the condition variable;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void * printEven(unsigned long id)
{
pthread_mutex_lock(&mymutex);
evenThreads++;
printf("TID: %lu, Hello from even\n", id);
// this condition checks whether even threads have finished executing
if(evenThreads + oddThreads >= 10) {
EVEN_DONE = TRUE;
pthread_cond_broadcast(&cond);
}
pthread_mutex_unlock(&mymutex);
return NULL;
}
void * printOdd(unsigned long id)
{
pthread_mutex_lock(&mymutex);
while (!EVEN_DONE) {
oddThreads++;
pthread_cond_wait(&cond, &mymutex);
printf("TID: %lu, Hello from odd\n", id);
}
pthread_mutex_unlock(&mymutex);
return NULL;
}
void * threadFunc(void *arg)
{
unsigned long id = (unsigned long)pthread_self();
if (id % 2 == 0)
{
printEven(id);
}
else
{
printOdd(id);
}
return NULL;
}
int main()
{
pthread_t* threads;
int num_threads = 10;
int i, j;
threads = malloc(num_threads * sizeof(threads));
for ( i = 0; i < 10; i++) {
pthread_create(&threads[i], NULL, threadFunc, NULL);
}
for ( j = 0; j < 10; j++) {
pthread_join(threads[j], NULL);
}
printf("Finished executing all threads\n");
return 0;
}
但是,当我运行代码时,它不会产生所需的输出。我得到的输出是:
显然,似乎所有线程ID都是偶数。但是,我认为我的代码存在问题。我究竟做错了什么?如何实现所需的输出?
(注意:对于POSIX线程和一般的多线程,我在初学者级别)
提前致谢。
答案 0 :(得分:3)
在POSIX中无法保证pthread_t
返回的pthread_self()
类型是可以强制转换为unsigned long
的数字类型 - 它可以是结构类型,示例
如果要以符合POSIX的方式编写代码,则需要自己分配数字线程ID。例如,您可以:
unsigned long allocate_id(void)
{
static unsigned long next_id = 0;
static pthread_mutex_t id_lock = PTHREAD_MUTEX_INITIALIZER;
unsigned long id;
pthread_mutex_lock(&id_lock);
id = next_id++;
pthread_mutex_unlock(&id_lock);
return id;
}
然后在你的主题中使用:
unsigned long id = allocate_id();
自己控制ID的分配也允许您控制序列 - 例如,在这种情况下,您可以确保按顺序分配ID,以便您同时拥有奇数和偶数ID。