- 论坛徽章:
- 0
|
现在看到三个线程并行的很好了:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <sched.h>
#define NUM 100
int a = 0, b = 0;
void rand_cal()
{
printf("In thread %d: (a, b) == (%d, %d)\n", (int)pthread_self(), a, b);
}
void *thread1(void *args)
{
int i;
pthread_detach(pthread_self());
for (i = 0; i < NUM; ++i) {
rand_cal();
++a;
}
return NULL;
}
void *thread2(void *args)
{
int i;
pthread_detach(pthread_self());
for (i = 0; i < NUM; ++i) {
rand_cal();
++b;
}
return NULL;
}
int main()
{
pthread_t t1, t2;
int i;
if (pthread_create(&t1, NULL, thread1, NULL)) {
fprintf(stderr, "Create thread t1 failed!\n");
abort();
}
if (pthread_create(&t2, NULL, thread2, NULL)) {
fprintf(stderr, "Create thread t2 failed!\n");
abort();
}
for (i = 0; i < NUM; ++i) {
rand_cal();
printf("Now a == %d; b == %d\n", a, b);
}
exit(0);
} |
|