zoukankan      html  css  js  c++  java
  • LInux下Posix的传统线程示例

    简介

    Linux线程是需要连接pthreat库,线程的使用比进程更灵活,需要注意的是线程间的互斥,或者说是资源共享问题。
    C++11之后,C++标准库也引入了线程,并且使用非常方便,以后再介绍,这里先发一个简单的线程示例代码。

    代码

    #include <stdio.h>
    #include <pthread.h>
    #include <string.h>
    #include <stdlib.h>
    
    
    char message[32]={"Hello world!"};
    void *thread_function(void *arg);
    
    
    void *thread_function(void *arg)
    {
        printf("thread_fonction is runing , argument is %s
    ", (char *)arg);
        strcpy(message, "marked by thread");
    
        printf("thread_function finished
    ");
        pthread_exit("Thank you for the cpu time
    ");	
    }
    
    
    int
    main(int argc, char **argv)
    {   
        pthread_t a_thread;
        void *thread_result;
    
        if(pthread_create(&a_thread, NULL, thread_function, (void*)message ) < 0)
    	{
    		perror("pthread_create error:");
    		exit(-1);
    	}
    	
        printf("writing for the thread to finish
    ");
        if(pthread_join(a_thread, &thread_result) < 0)
        {
            perror("pthread_join error:");
            exit(0);
        }
    
        printf("in main, thread is exist, marked msg: %s 
    ", message);
    
        exit(0);
    }
    

    编译

    编译的时候,需要加上pthread线程库

    gcc pthreat.c -o test -lpthread
    

    运行

    程序启动后,主程序中,创建线程,然后等待线程退出,在线程函数里,会把message字符串修改掉。

    ./test 
    in main, writing for the thread to finish
    in thread, thread_fonction is runing , argument is Hello world!
    in thread, thread_function finished
    in main, thread is exist, marked msg: marked by thread 
    
  • 相关阅读:
    博客发在oschina
    博客发在oschina
    C#将dll打包到程序中
    C#将dll打包到程序中
    WPF checkbox文字下掉
    WPF checkbox文字下掉
    手机1520 win8.1升级win10
    CRITICAL **: Couldn't acquire global lock, snapshots will not be consistent: Access denied
    [学习笔记]Dsu On Tree
    手机1520 win8.1升级win10
  • 原文地址:https://www.cnblogs.com/fensnote/p/13436443.html
Copyright © 2011-2022 走看看