注意创建线程的那一瞬间继承前面的所有数据,之后线程与其他线程之间的数据就分开了
未加锁版:
#include<stdio.h> #include<pthread.h> using namespace std; int num=100; void* tprocess1(void* args) { while(num>0){ int i=num; printf("tprocess1--%d\n",i); i--; num=i; } return NULL; } void* tprocess2(void* args) { while(num>0){ int i=num; printf("tprocess2--%d\n",i); i--; num=i; } return NULL; } int main() { pthread_t t1; pthread_t t2; pthread_create(&t1,NULL,tprocess1,NULL); pthread_create(&t2,NULL,tprocess2,NULL); //注意这句开始的时候num可能已经不是为100了,假设为97,则tprocess2继承97往下输出 pthread_join(t1,NULL); pthread_join(t2,NULL); return 0; }加锁版:(规规矩矩的从100输出到0)
#include<stdio.h> #include<pthread.h> using namespace std; pthread_mutex_t abc; int num=100; void* tprocess1(void* args) { while(num>0){ pthread_mutex_lock(&abc); int i=num; printf("tprocess1--%d\n",i); i--; num=i; pthread_mutex_unlock(&abc); } return NULL; } void* tprocess2(void* args) { while(num>0){ pthread_mutex_lock(&abc); int i=num; printf("tprocess2--%d\n",i); i--; num=i; pthread_mutex_unlock(&abc); } return NULL; } int main() { pthread_t t1; pthread_t t2; pthread_mutex_init(&abc,NULL); pthread_create(&t1,NULL,tprocess1,NULL); pthread_create(&t2,NULL,tprocess2,NULL); pthread_join(t1,NULL); pthread_join(t2,NULL); pthread_mutex_destroy(&abc) return 0; }
