#include #include #include #include using namespace std; struct data { unsigned long long count; unsigned long long *value; pthread_mutex_t *value_lock; }; void *worker(void *args) { data *t = (data *)args; for (long long i = 0; i < t->count; i++) { pthread_mutex_lock(t->value_lock); t->value[0]++; pthread_mutex_unlock(t->value_lock); } return NULL; } int main(int argc, char **argv) { const int COUNT = argc > 1 ? atoi(argv[1]) : 1000000000; const int THREADS = argc > 2 ? atoi(argv[2]) : 1; vector args(THREADS); vector threads(THREADS); unsigned long long value = 0; pthread_mutex_t value_lock; pthread_mutex_init(&value_lock, NULL); for (int i = 0; i < THREADS; i++) { args[i].count = COUNT; args[i].value = &value; args[i].value_lock = &value_lock; pthread_create(&threads[i],NULL,worker,&args[0]); } for (int i = 0; i < THREADS; i++) { pthread_join(threads[i], NULL); } printf("value=%llu\n", value); }