int main()
{
pthread_mutex_init(&mut, NULL);
printf("l am master function \n");
thread_create();
printf("l am master function,l am waiting for threads to over\n");
thread_wait();
return 0;
}
gcc -o thread_example -c thread_example.c -pthread
./thread_example 执行程序结果如下:
l am master function
create thread1 success
thread1: l am thread 1
create thread2 success
l am master function,l am waiting for threads to over
thread2: l am thread2
thread1:num = 0
thread2:num = 0
thread1:num = 2
thread2:num = 3
thread1:num = 4
thread2:num = 5
thread1:num = 6
thread1:num = 7
thread2:num = 8
thread1:num = 9
thread2:num = 10
thread1: master function waiting for me to done?
now thread1 is over
thread2: master function is waiting for me?
now thread2 is over
再次执行程序结果如下:
l am master function
create thread1 success
thread1: l am thread 1
create thread2 success
l am master function,l am waiting for threads to over
thread1:num = 0
thread2: l am thread2
thread2:num = 1
thread1:num = 2
thread2:num = 3
thread1:num = 4
thread2:num = 5
thread1:num = 6
thread1:num = 7
thread2:num = 8
thread1:num = 9
thread2:num = 10
thread1: master function waiting for me to done?
now thread1 is over
thread2: master function is waiting for me?
now thread2 is over
再次结果是不一样的:对于num的第一次的值,当thread1中num =0时,thread2中的num 就不应该再出现num = 0的可能了,但却出现了,反复执行程序,结果如上所示。
不知道这是为什么,请高手指点,谢谢。
线程相关的一些操作:
pthread_t-----> typedef unsigned long int pthread_t
pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg)
pthread_t thread[2];
pthread_mutex_t mut;
int num = 0;
int i = -1;
void *thread1()
{
printf("thread1: l am thread 1\n");
for(i = 0; i < MAX; i++)
{
printf("thread1:num = %d\n",num);
pthread_mutex_lock(&mut);
num++;
pthread_mutex_unlock(&mut);
sleep(2);
}
printf("thread1: master function waiting for me to done?\n");
pthread_exit("------------------thread1\n");
}
void *thread2()
{
printf("thread2: l am thread2\n");
for(i = 0; i < MAX; i++)
{
printf("thread2:num = %d\n",num);
pthread_mutex_lock(&mut);
num++;
pthread_mutex_unlock(&mut);
sleep(3);
}
printf("thread2: master function is waiting for me? \n");
pthread_exit("this is thread2----------->\n");
}
int main()
{
pthread_mutex_init(&mut, NULL);
printf("l am master function \n");
thread_create();
printf("l am master function,l am waiting for threads to over\n");
thread_wait();
return 0;
}