我正在研究线程和并发编程。从课堂上提供的内容中尝试了这个基本的例子:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 8
void *printGoGators(void *noArg)
{
printf("Go Gators!\n");
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc, t;
for (t = 0; t < NUM_THREADS; t++)
{
printf("Creating thread %d\n", t);
rc = pthread_create(&threads[t],
NULL,
printGoGators,
NULL);
if(rc)
{
printf("ERROR %d", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
此代码生成以下输出。 :
Creating thread 0
Creating thread 1
Go Gators!
Creating thread 2
Go Gators!
Creating thread 3
Go Gators!
Creating thread 4
Go Gators!
Creating thread 5
Go Gators!
Creating thread 6
Go Gators!
Creating thread 7
Go Gators!
Go Gators!
为什么Go Gators!
在所有线程的相应Creating thread #
之后不能直接打印?
请帮忙!
答案 0 :(得分:4)
如果您的代码看起来像这样,那么输出将按您期望的顺序排列:
for (t = 0; t < NUM_THREADS; t++)
{
printf("Creating thread %d\n", t);
printGoGators(NULL);
}
因此,您假设线程将按照创建它们的顺序执行。但是,这种假设是不正确的 - 线程可以按任何顺序执行。
答案 1 :(得分:1)
创建线程后,由操作系统决定执行哪些顺序线程。您可以使用互斥锁和条件来控制它,以锁定线程让另一个线程运行然后解锁它。
与接受的答案不同,此示例使用线程,而不仅仅是在循环中打印。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 8
pthread_mutex_t myMutex; // Declere global mutex
pthread_cond_t myCondition; // Declere global condition
void *printGoGators(void *arg) {
printf("Go Gators! %i\n", *(int*)arg);
delete (int*) arg;
pthread_cond_signal(&myCondition); // Signal that a condition is met
return NULL;
}
int main(int argc, char *argv[]) {
pthread_mutex_init(&myMutex, NULL); // Initialize mutex
pthread_cond_init (&myCondition, NULL); // Initialize condition
pthread_t threads[NUM_THREADS];
int rc, t;
for (t = 0; t < NUM_THREADS; t++) {
int* n = new int;
*n = t;
printf("Creating thread %d\n", t);
rc = pthread_create(&threads[t],
NULL,
printGoGators,
n);
if(rc) {
printf("ERROR %d", rc);
exit(-1);
}
pthread_cond_wait(&myCondition, &myMutex); // waite for condition
}
pthread_exit(NULL);
}
结果:
Creating thread 0
Go Gators! 0
Creating thread 1
Go Gators! 1
Creating thread 2
Go Gators! 2
Creating thread 3
Go Gators! 3
Creating thread 4
Go Gators! 4
Creating thread 5
Go Gators! 5
Creating thread 6
Go Gators! 6
Creating thread 7
Go Gators! 7
主线程创建循环:创建一个线程,然后等待条件。
新主题:打印一条消息,然后发出满足条件的信号。
这样就可以管理执行顺序。