如何使用线程和一个全局变量来完成任务?
如果您正在使用Linux,您可以使用POSIX库为C编程语言线程。图书馆是。然而,作为替代方案,在MSVC上的gcc和g++和(具有旧版本)得到很好支持的相当便携且相对非侵入性的库是openMP。
它不是标准的C和C++,但OpenMP本身就是一个标准。
如何在Linux中按期望的顺序安排线程?
要实现所需的打印操作,您需要有一个全局变量,可以通过您的两个线程访问该变量。两个线程轮流访问全局变量variable并执行操作(increment和print)。但是,要实现desired order,则需要有一个mutex。互斥量是一种互斥信号量,一次只允许一个寄存器的信号量的特殊变体。当您拥有资源实例(global variable in your case)并且该资源正由两个线程共享时,可以使用它。锁定该互斥锁后的线程可以独占访问资源实例,并且在完成操作后,线程应释放其他线程的互斥锁。
您可以从here的开始使用线程和互斥锁。
您的问题的可能的解决方案之一可能是这个程序在下面给出。但是,我建议你自己试试看,然后看看我的解决方案。
#include
#include
#include
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
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
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;
}