|
一个进程产生了一些线程以后,那么这个主进程和线程之间是什么关系?怎样联系?
请看下列这段代码:
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- void task1(int *counter);
- void task2(int *counter);
- void cleanup(int counter1, int counter2);
- int g1 = 0;
- int g2 = 0;
- int main(int argc, char *argv[])
- {
- pthread_t thrd1, thrd2;
- int ret;
- ret = pthread_create(&thrd1, NULL, (void *)task1, (void *)&g1);
- if (ret) {
- perror("pthread_create: task1");
- exit(EXIT_FAILURE);
- }
- ret = pthread_create(&thrd2, NULL, (void *)task2, (void *)&g2);
- if (ret) {
- perror("pthread_create: task2");
- exit(EXIT_FAILURE);
- }
- pthread_join(thrd2, NULL);
- pthread_join(thrd1, NULL);
- cleanup(g1, g2);
- exit(EXIT_SUCCESS);
- }
- void task1(int *counter)
- {
- while (*counter < 5) {
- printf("task1 count: %d\n", *counter);
- (*counter)++;
- sleep(1);
- }
- }
- void task2(int *counter)
- {
- while (*counter < 5) {
- printf("task2 count: %d\n", *counter);
- (*counter)++;
- }
- }
- void cleanup(int counter1, int counter2)
- {
- printf("total iterations: %d\n", counter1 + counter2);
- }
复制代码
其中调用了两次pthread_join使指定的线程挂起。因此可以看到线程一执行完后,线程2才开始执行。但如果我去掉这两句,那么线程1(执行task1的线程)输出一行后,便是线程2输出。通过多次的运行,线程2的输出次数不定。而线程一肯定是只输出一次,并且一定是在第一行输出。那么请问这种现象是怎么回事? |
|