您的位置:首页 > 其它

pthread_create()的基本使用

2016-07-28 16:06 363 查看
Linux系统下使用线程

其中变量为:typedef unsigned long int pthread_t;

1建立一个线程:



//hellothread.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *function(void *arg);

int main(int argc, char *argv[]){
pthread_t thread1;
pthread_create(&thread1,NULL,function,(char*)"111");
pthread_join(thread1,NULL);
return 0;
}

void *function(void *arg){
char *m;
m = (char *)arg;
while(*m != '\0') {
printf("%c",*m);
fflush(stdout);
m++;
sleep(1);
}
printf("\n");
}

2多个线程同时执行:



//hellothread.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *function(void *arg);

pthread_mutex_t mutex;

int main(int argc, char *argv[]){
pthread_t thread1, thread2, thread3;
pthread_mutex_init(&mutex,NULL);
pthread_create(&thread1,NULL,function,(char*)"111");
pthread_create(&thread2,NULL,function,(char*)"222");
pthread_create(&thread3,NULL,function,(char*)"333");
while (1) {
sleep(1);
}
return 0;
}

void *function(void *arg){
char *m;
m = (char *)arg;
while(*m != '\0') {
printf("%c",*m);
fflush(stdout);
m++;
sleep(1);
}
printf("\n");
}

因为使用了while()所以需要手动Ctrl+c进行中断程序运行;

3使用线程互斥锁进行分别执行:



//hellothread.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *function(void *arg);

pthread_mutex_t mutex;//互斥锁

int main(int argc, char *argv[]){
pthread_t thread1, thread2, thread3;
pthread_mutex_init(&mutex,NULL);
pthread_create(&thread1,NULL,function,(char*)"111");
pthread_create(&thread2,NULL,function,(char*)"222");
pthread_create(&thread3,NULL,function,(char*)"333");
while (1) {
sleep(1);
}
return 0;
}

void *function(void *arg)
{
char *m;
m = (char *)arg;
pthread_mutex_lock(&mutex);
while(*m != '\0')
{
printf("%c",*m);
fflush(stdout);
m++;
sleep(1);
}
printf("\n");
pthread_mutex_unlock(&mutex);
}

*tips:

案例1中调用pthread_join()等待线程结束后退出主程序,

也可以使用while()循环来阻住程序退出;

推荐使用pthread_join();

int pthread_create(); 返回值为0时线程创建成功;

存在的疑问:多次测试均是线程执行顺序与建立顺序相反;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: