如何使用线程和一个全局变量完成任务?
如果您使用Linux,您可以使用POSIX 库在C 编程语言中进行线程化。图书馆是<pthread.h>。然而,作为替代方案,一个非常便携且相对非侵入性的库,在gcc 和g++ 上得到很好的支持,MSVC 上的(旧版本)是openMP。
它不是标准的 C 和 C++,但 OpenMP 本身就是一个标准。
如何在 linux 中按所需顺序调度线程?
为了实现你想要的打印操作,你需要一个全局变量,它可以被你的两个线程访问。两个线程轮流访问全局变量variable并执行操作(increment和print)。但是,要实现desired order,您需要有一个mutex。互斥量是一种互斥信号量,是信号量的一种特殊变体,一次只允许一个储物柜。当您有一个资源实例 (global variable in your case) 并且该资源由两个线程共享时,可以使用它。锁定该互斥锁后的线程可以独占访问资源实例,并且在完成其操作后,线程应该为其他线程释放互斥锁。
您可以从here 中的<pthread.h> 中的线程和互斥锁开始。
您的问题可能的解决方案之一可能是该程序如下所示。不过,我建议你自己找试试看,然后看看我的解决方案。
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t lock;
int variable=0;
#define ONE_TIME_INC 5
#define MAX 100
void *thread1(void *arg)
{
while (1) {
pthread_mutex_lock(&lock);
printf("Thread1: \n");
int i;
for (i=0; i<ONE_TIME_INC; i++) {
if (variable >= MAX)
goto RETURN;
printf("\t\t%d\n", ++variable);
}
printf("Thread1: Sleeping\n");
pthread_mutex_unlock(&lock);
usleep(1000);
}
RETURN:
pthread_mutex_unlock(&lock);
return NULL;
}
void *thread2(void *arg)
{
while (1) {
pthread_mutex_lock(&lock);
printf("Thread2: \n");
int i;
for (i=0; i<ONE_TIME_INC; i++) {
if (variable >= MAX)
goto RETURN;
printf("%d\n", ++variable);
}
printf("Thread2: Sleeping\n");
pthread_mutex_unlock(&lock);
usleep(1000);
}
RETURN:
pthread_mutex_unlock(&lock);
return NULL;
}
int main()
{
if (pthread_mutex_init(&lock, NULL) != 0) {
printf("\n mutex init failed\n");
return 1;
}
pthread_t pthread1, pthread2;
if (pthread_create(&pthread1, NULL, thread1, NULL))
return -1;
if (pthread_create(&pthread2, NULL, thread2, NULL))
return -1;
pthread_join(pthread1, NULL);
pthread_join(pthread2, NULL);
pthread_mutex_destroy(&lock);
return 0;
}