这一周前两天把线程控制看完了,在这里总结一下我的易错点以及需要注意的点。
1、进程跟线程的关系:在我看来单一进程就是一个大的线程,但是如果进程中创建了多个线程之后,它就成了父线程,如果父线程结束,那么子线程也就结束了。这点跟子进程不同。
2、多个子线程是共用进程的存储空间,不像子进程一样,是自己申请一个存储空间。
3、pthread_creat函数,原形是
int
pthread_create(pthread_t *
thread
,
const
pthread_attr_t *attr,
void
*(*start_routine) (
void
*),
void
*arg);
这个函数的原形打眼看很不好理解,说一下四个参数分别代表的含义:
第一个参数:指向线程标识符的指针。第二个参数:用来设置线程属性。
第三个参数:是运行函数的起始位置。第四个参数:即将运行函数的参数。
第三个参数是一个整体,表示一个函数:贴一个例子:
标记的地方可以跟第三个参数比较一下,其实第三个参数就是代表了被调函数的命名原形。#include <unistd.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> int * thread(void * arg) //看这里 { pthread_t tid1; tid1 = pthread_self(); printf("tid1 = %d\n",tid1); return NULL; } int main(int argc, char *argv[]) { pthread_t tid2; printf("i am master pthread:%d\n",pthread_self()); tid2 = pthread_create(&tid2, NULL ,(void *)thread , NULL ); if( tid2 != 0 ) { perror("pthread creation is failed!\n"); exit(0); } sleep(1); return EXIT_SUCCESS; }
4、linux命令:eog 可以查看图片。
5、pthread_t :
定义:typedef unsigned long int pthread_t;
用途:pthread_t 用于声明线程ID。sizeof(pthread_t) = 4;
跟pthread_attr_t区别开,pthread_t是用来设置线程属性的。
6、pthread_attr_t:
定义;typedef struct {
int datachstate;(线程的分离状态)
int schedparam;(线程的调度策略)
struct sched_param schedparam;(线程的调度参数)
int inheritsched;(线程的继承性)
int scope;(线程的作用域)
size_t guardsize;(线程栈末尾的警戒缓冲区大小)
int stackaddr_set;
void * stackaddr;(线程栈位置)
size_t stacksize;(线程栈大小)
}pthread_addr_t;
7、pthread_addr_t 设置为PTHREAD_CREATE_DETACHED,则新线程不能用pthread_join()来同步,且在退出时候自行释放所占用的资源。
8、pthread_cleanup_push()跟pthread_cleanup_pop()是一组的,所以要同时出现。贴一段代码:
#include <unistd.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; void * thread1(void * arg) { pthread_cleanup_push(pthread_mutex_unlock,&mutex); while(1) { printf("thread1 is running\n"); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond,&mutex); printf("thread1 applied the condition\n"); pthread_mutex_unlock(&mutex); sleep(4); } pthread_cleanup_pop(0); } void * thread2(void * arg) { while(1) { printf("thread2 is running!\n"); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond,&mutex); printf("thread2 applied the condition\n"); pthread_mutex_unlock(&mutex); sleep(1); } } int main(int argc, char *argv[]) { pthread_t tid1,tid2; printf("condition variable study!\n"); pthread_mutex_init(&mutex,NULL); pthread_cond_init(&cond,NULL); pthread_create(&tid1,NULL,(void *)thread1,NULL); pthread_create(&tid2,NULL,(void *)thread2,NULL); do { pthread_cond_signal(&cond); }while(1); sleep(50); pthread_exit(0); return EXIT_SUCCESS; }
9、互斥锁可以单独使用,避免了多线程对同一文件的写入操作。但环境变量需要配合互斥锁一起使用。
linux c学习之线程控制
最新推荐文章于 2023-02-06 16:49:35 发布
博主分享了在学习Linux C语言中关于线程控制的心得体会,重点包括进程与线程的区别、多线程共享存储空间的特点以及pthread_create函数的使用注意事项。
摘要由CSDN通过智能技术生成