- #include <stdio.h>
-
#include <pthread.h>
-
#include <time.h>
-
static int count=0;
-
void *test1()
-
{
-
printf("pthread 1\n");
-
int i=0;
-
while(i++!=11111110) //如果数据太小在线程让出cpu之前就已经完成操作,就看不到不一致的效果鸟~~
-
{
-
count++;
-
}
-
return NULL;
-
}
-
-
void *test2()
-
{
-
printf("pthread 2\n");
-
int i=0;
-
while(i++!=11111160)
-
{
-
count++;
-
}
-
return NULL;
-
}
-
-
int main()
-
{
-
pthread_t a,b;
-
pthread_create(&a,NULL,test1,NULL); //创建新线程,默认线程属性
-
pthread_create(&b,NULL,test2,NULL);
-
sleep(2);
-
printf("%d\n",count);
- }
- coder@coder:~/C and C++/pthread$ ./a.out
-
pthread 1
-
pthread 2
-
14280152
-
coder@coder:~/C and C++/pthread$ ./a.out
-
pthread 1
-
pthread 2
-
15333212
-
coder@coder:~/C and C++/pthread$ ./a.out
-
pthread 1
-
pthread 2
- 13588147
- #include <stdio.h>
-
#include <pthread.h>
-
#include <time.h>
-
static int count=0;
-
pthread_mutex_t p_lock; //定义互斥量
-
void *test1()
-
{
-
pthread_mutex_lock(&p_lock); //加锁 ,如果被其他线程抢先一步,就阻塞等待
-
printf("pthread 1\n");
-
int i=0;
-
while(i++ != 11111110)
-
{
-
count++;
-
}
-
pthread_mutex_unlock(&p_lock); //解锁
-
return NULL;
-
}
-
-
void *test2()
-
{
-
pthread_mutex_lock(&p_lock);
-
printf("pthread 2\n");
-
int i=0;
-
while(i++ != 11111160)
-
{
-
count++;
-
}
-
pthread_mutex_unlock(&p_lock);
-
return NULL;
-
}
-
-
int main()
-
{
-
pthread_t a,b;
-
pthread_mutex_init(&p_lock,NULL); //使用默认属性初始化互斥量
-
if(pthread_create(&a,NULL,test1,NULL)!=0) //创建新线程,默认线程属性
-
{
-
printf("can‘t create thread\n");
-
}
-
if(pthread_create(&b,NULL,test2,NULL)!=0)
-
{
-
printf("can‘t create thread\n");
- }
- pthread_mutex_destroy(&p_lock); //销毁
-
sleep(2);
-
printf("%d\n",count);
- }
- coder@coder:~/C and C++/pthread$ ./a.out
-
pthread 1
-
pthread 2
-
22222270
-
coder@coder:~/C and C++/pthread$ ./a.out
-
pthread 1
-
pthread 2
-
22222270
-
coder@coder:~/C and C++/pthread$ ./a.out
-
pthread 1
-
pthread 2
- 22222270
gcc pthread.c -lphtread