原文:http://blog.csdn.net/cn_wk/article/details/62236057
hello thread!
-
声明线程A的端口号
#include <pthread.h> pthread_t tid;
-
定义线程运行函数
void thread_function(void *args) { printf("thread_function is called! "); //注意区别 cout << "thread_function is called! << endl; 和上一行 }
-
创建线程
pthread_create(&tid, NULL, &thread_function, NULL);
-
(optional)阻塞: 挂起当前线程,直到tid线程结束
pthread_join(tid, NULL);
好了,这样就可以启一个线程了,完整代码如下:
#include<unistd.h> #include<stdio.h> #include<cstring> #define MAX_THREAD 2 pthread_t thread[MAX_THREAD]; pthread_mutex_t mut; int num = 0; void* thread1(void *args) { printf("hi, I am thread1 "); for(int i=0; i < 6; i++){ pthread_mutex_lock(&mut); printf("[thread1]num=%d, i=%d ", num, i); num ++; pthread_mutex_unlock(&mut); sleep(2); } pthread_exit(NULL); } void* thread2(void *args) { printf("hi, I am thread2 "); for(int i = 0; i < 10; i++) { pthread_mutex_lock(&mut); printf("[thread2]num=%d, i=%d ", num, i); num ++; pthread_mutex_unlock(&mut); sleep(3); } pthread_exit(NULL); } void thread_create() { memset(&thread, 0, sizeof(thread)); if( 0!=pthread_create(&thread[0], NULL, thread1, NULL)) printf("thread1 create faild "); else printf("thread1 established "); if( 0 != pthread_create(&thread[1], NULL, thread2, NULL)) printf("thread2 create faild "); else printf("thread2 established "); } void thread_wait() { if(0 != thread[0]) { pthread_join(thread[0], NULL); printf("thread 1 is over "); } if(0 != thread[1]) { pthread_join(thread[1], NULL); printf("thread 2 is over "); } } int main() { pthread_mutex_init(&mut, NULL); printf("main thread: creating threads... "); thread_create(); printf("main thread: waiting threads to accomplish task... "); thread_wait(); return 0; }
代码,得到结果:
tmain thread: creating threads…
thread1 established
hi, I am thread1
[thread1]num=0, i=0
thread2 established
main thread: waiting threads to accomplish task…
hi, I am thread2
[thread2]num=1, i=0
[thread1]num=2, i=1
[thread2]num=3, i=1
[thread1]num=4, i=2
[thread2]num=5, i=2
[thread1]num=6, i=3
[thread1]num=7, i=4
[thread2]num=8, i=3
[thread1]num=9, i=5
[thread2]num=10, i=4
thread 1 is over
[thread2]num=11, i=5
[thread2]num=12, i=6
[thread2]num=13, i=7
[thread2]num=14, i=8
[thread2]num=15, i=9
thread 2 is over
OK,现在说一下pthread_create方法的原型
pthread_create方法
作用
- 创建线程
原型
```
int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict arg);
```
参数
- 第一个参数是指向线程标识符的指针
- 第二个参数用来设置线程的属性
- 第三个参数是线程运行函数的首地址
- 第四个参数是线程运行函数的参数
返回值
- 若成功,则返回0;否则,返回错误编号。
pthread_join方法
作用
- 这个函数是一个线程阻塞的函数
- 等待线程结束再继续往下执行,要不然主进程和下面的线程并行执行
原型
extern int pthread_join __P ((pthread_t __th, void **__thread_return))
参数
- 第一个参数是被等待线程的标识符
- 第二个参数是用户自定义的指针。用来存储被等待线程的返回值