112207202126 周泽安 pthread
- 格式:doc
- 大小:53.78 KB
- 文档页数:4
#include <stdio.h>
#include <pthread.h>
void *myThread1(void)
{
int i;
for (i=0; i<5; i++)
{
printf("This is the 1st pthread,created by zieckey.\n"); }
}
void *myThread2(void)
{
int i;
for (i=0; i<5; i++)
{
printf("This is the 2st pthread,created by zieckey.\n");
}
}
int main()
{
int i=0, ret=0;
pthread_t id1,id2;
/*创建线程1*/
ret = pthread_create(&id1, NULL, (void*)myThread1, NULL);
if (ret)
{
printf("Create pthread error!\n");
return 1;
}
/*创建线程2*/
ret = pthread_create(&id2, NULL, (void*)myThread2, NULL);
if (ret)
{
printf("Create pthread error!\n");
return 1;
}
pthread_join(id1, NULL);
pthread_join(id2, NULL);
return 0;
}
Linux 中cpu的运行是并行结构,只要有空余就会运行,当pthread1 睡眠时,pthread2就
会运行,当pthread2睡眠时,pthread1就会运行
开始
创建线程ptread1 创建线程pthread2
失败成功成功失败
输出Create
pthread error输出5遍this is the 2st
pthread created by zieckey
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int a = 1;
void *create1(void *arg)
{ printf("new pthread ... \n");
printf("a=%d \n",a);
return (void *)0;
}
void *create2(void *arg)
{printf("new pthread ...\n");
printf("a=%d \n",a);
return (void *)0;
}int main(int argc,char *argv[])
{ pthread_t tidp;
int error;
int a=5;
printf("a = %d\n",a);
error=pthread_create(&tidp, NULL, create1, NULL); if(error!=0)
{ printf("new thread is not create ... \n"); return -1; }
printf(new thread is created ...\n);
sleep(1);
error=pthread_create(&tidp, NULL, create2, NULL);
if(error!=0)
{ printf("new thread is not create ... \n");
return -1; }
printf("new thread is created ... \n");
sleep(1);
return 0;
}
开始
建立线程creat1 建立线程create2
定义两个系数
int a=5,error;
输出a=5
引用线程create1
输出new pthread 。
a=1
输出new thread is not
create 。
输出new thread is
create 。
Error!=0。