怎样实现Mycat读写分离与负载均衡
725
2022-09-24
unix高级环境编程---11章 线程 学习
零散知识。
1.线程id--- 进程id的类型是pid_t, 线程id的类型是pthread_t;
比较两个线程id:
#include
int pthread_equal ( pthread_t tid1, pthread_t tid2 );
获得自身的线程id:
pthread_t pthread_self(void)
2.线程创建
int pthread_create( pthread_t *restrict tidp, const pthread_attr_t *restrict attr,
void *(*start_rtn)(void *), void *restrict arg );
接下来是打印线程id的例子:
#include
void printids(const char *s){ pid_t pid; pthread_t tid; pid = getpid(); tid = pthread_self(); printf("%s pid %u tid %u (0x%x)\n",s, (unsigned int)pid, (unsigned int)tid, (unsigned int) tid);
} void *thr_fn(void *arg){ printids("new thread: "); return ((void*)0);
}
int main(){ int err = 0; err = pthread_create(&ntid, NULL, thr_fn, NULL); //err = pthread_create(&ntid, NULL, thr_fn, NULL); if(err!=0){ printf("%s\n", strerror(err) );
} printids("main thread:"); sleep(1); exit(0); }
使用ubuntu,eclipse编译,提示找不到pthread_create. 头文件是定义了,但是没有连接线程库。 需要设置eclipse。 选择工程--属性--c、c++build--settings---gcc c linker---libraries, 添加库 pthread。 再次编译运行。ok。
main thread: pid 2164 tid 3079145152 (0xb78806c0) new thread: pid 2164 tid 3079142256 (0xb787fb70)
3、线程终止
void *thr_fn1(void *arg){ printf("thread 1 returning\n"); return ((void* )1);
}
void *thr_fn2(void *arg){ printf("thread 2 exiting\n"); pthread_exit((void *)1);
}
int main(){ int err; pthread_t tid1, tid2; void *tret; err = pthread_create(&tid1, NULL, thr_fn1, NULL); if( err != 0){ printf("can't create thread 1:%s\n", strerror(err)); } err = pthread_create(&tid2, NULL, thr_fn2, NULL); if( err!=0){ printf("can't create thread 2:%s\n", strerror(err)); } err = pthread_join(tid1, &tret); if(err!=0){ printf("can't join with thread 1:%s\n", strerror(err));
} printf(" thread 1 exit code %d\n", (int)tret); err = pthread_join(tid2, &tret); if(err!=0){ printf("can't join eith thread 2:%s\n", strerror(err)); } printf("thread 2 exit code %d\n", (int)tret); exit(0); }
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。