📄 testpthread1.c
字号:
/*http://www.pudn.com:7122/s.asp?kw=linux%20c%20多线程&pos=40
http://www.pudn.com/downloads30/sourcecode/database/detail97410.html
作者:ddxxkk
多线程设计 1
线程的调用
程序名为 testt.c
在编译时一定要有 -lpthread
cc -lpthread -o testt testt.c
*/
#include <pthread.h>
#include <stdio.h>
void *testn(void *arg) //线程1
{
int n=1,nnn,*inn=(int *)arg;
pthread_t id;
id=pthread_self();
printf(" Pthread is create id=%d \n",id);
for (n=1;n<4 ;n++)
{
printf(" id%d and *arg=%d n=%d \n",id,*inn,n);
sleep(1); //停1秒钟
}
printf(" Pthread is end id=%d \n",id);
*inn=*inn*11;
/*
pthread_exit(void *vp);
如果用返回值要用外部指针
*/
pthread_exit(inn);
// pthread_exit(NULL);
}
void tests(void *arg)
{
char *message;
//pthread_detach(pthread id) 设计脱离进程,不可pthread_join
printf("to detach %d \n",pthread_detach(pthread_self()));
message = (char *) arg;
printf("%s \n ", message);
}
int main()
{
pthread_t threadid[4];
int n0=100000,n1=200000,n2=30000,n3=40000;
int *nb;
char *mess1 = " This is dthread 1";
char *mess2 = " This is dthread 2";
nb=&n1;
n1=99000;
printf(" Begin \n");
/* pthread_create( &a_thread, a_thread_attribute, (void *)&thread_function,(void *) &some_argument);
// pthread_create(pthread_t *, const pthread_attr_t *, (void *) function, void *)'
// 线程ID(不能为NULL) 线程类型 线程函数(不能为NULL) 参数
线程类型:PTHREAD_CREATE_DETACHED 脱离的
PTHREAD_CREATE_JOINABLE 可汇合的(一般)
SCHED_OTHER 非实时调度
SCHED_FIFO 先进先出
SCHED_RR 随机
一般用 NULL 默认值
*/
pthread_create(&threadid[0],NULL,testn,(int *)&n0);
pthread_create(&threadid[1],NULL,testn,nb);
pthread_create(&threadid[2],NULL,(void *)&tests,(void *)mess1);
pthread_create(&threadid[3],NULL,(void *)&tests,(void *)mess2);
printf(" end \n");
// sleep(10);
// 等线程结束 pthread_join(thread id)
// pthread_join(threadid[1],NULL);
printf(" now n0=%d \n",n0);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -