写一下简单的多线程吧,火车票售卖程序
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#include <unistd.h>
void *thread_function(void *arg);
pthread_mutex_t mutex;
int count = 100;
int main(int argc, char* argv[])
{
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_mutex_init(&mutex, NULL);
if(res != 0)
{
printf("Mutex init error!\n");
exit(-1);
}
res = pthread_create(&a_thread, NULL, thread_function, NULL);
if(res != 0)
{
printf("Thread create failure!\n");
exit(-1);
}
while(1)
{
pthread_mutex_lock(&mutex);
if(count > 0)
{
printf("Main Sell the NO %d tickek\n", count);
-- count;
}else{
pthread_mutex_unlock(&mutex);
break;
}
pthread_mutex_unlock(&mutex);
//sleep(1);
}
res = pthread_join(a_thread, &thread_result);
if(res != 0)
{
printf("Thread join failure!\n");
exit(-1);
}
printf("Thread join \n");
pthread_mutex_destroy(&mutex);
return 0;
}
void *thread_function(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(count > 0)
{
printf("Thread Sell the NO %d tickek\n", count);
-- count;
}else{
pthread_mutex_unlock(&mutex);
break;
}
pthread_mutex_unlock(&mutex);
//sleep(1);
}
}
编译时的命令为:
$ g++ test_selltickets.cpp -o test_selltickets -lpthread
此处需要链接多线程的库