pthread_create()的基本使用

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时线程创建成功;
存在的疑问:多次测试均是线程执行顺序与建立顺序相反;


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值