#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREAD 100 // 线程数
pthread_mutex_t mutex;
void* thread_increase(void* arg);
void* thread_reduce(void* arg);
long long sum = 0;
int main(int argc, const char * argv[])
{
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_destroy(pthread_mutex_t * mutex);
int pthread_mutex_lock(pthread_mutex_t * mutex);
int pthread_mutex_unlock(pthread_mutex_t * mutex);
pthread_t t_id[NUM_THREAD];
pthread_mutex_init(&mutex, NULL);
for (int index = 0; index < NUM_THREAD; ++index)
{
if (index % 2)
{
pthread_create(&(t_id[index]), NULL, thread_increase, NULL);
}
else
{
pthread_create(&(t_id[index]), NULL, thread_reduce, NULL);
}
}
for (int index = 0; index < NUM_THREAD; ++index)
{
pthread_join(t_id[index], NULL);
}
pthread_mutex_destroy(&mutex);
printf("sum = %lld\n",sum);
return 0;
}
void* thread_increase(void* arg)
{
pthread_mutex_lock(&mutex);
for (int index = 0; index < 100000; ++index)
{
sum += index;
}
pthread_mutex_unlock(&mutex);
return NULL;
}
void* thread_reduce(void* arg)
{
pthread_mutex_lock(&mutex);
for (int index = 0; index < 100000; ++index)
{
sum -= index;
}
pthread_mutex_unlock(&mutex);
return NULL;
}