C语言 线程创建与销毁基础接口(Windows & Linux)

Linux篇

  • 创建线程:
int pthread_create(
    pthread_t *tidp, //线程ID
    const pthread_attr_t *attr, //线程属性
    (void*)(*start_rtn)(void*), //线程函数
    void *arg);//传递给线程的参数
返回值:
成功-返回0
失败-返回错误码
  • 线程属性
    线程默认属性是joinable, 需主线程阻塞回收;
    若创建线程时设置属性为detach, 或子线程主动调用pthread_detach(), 则在线程返回时操作系统回收资源.

  • 线程资源回收
    注: 主动回收只针对属性为joinable的线程, detach是系统回收, 即子线程结束, 资源就释放.

  • 1.主动回收线程资源:

 int pthread_join(pthread_t thread, void **retval);
/* 
DESCRIPTION
       The  pthread_join() function waits for the thread specified by thread to terminate.  If that thread has already terminated, then pthread_join() returns immediately.  The thread specified by thread must be joinable.

RETURN VALUE
       On success, pthread_join() returns 0; on error, it returns an error number.
 */
  • 2.系统回收线程资源:
    方法1.主线程开启子线程之前设置detach属性:
    pthread_t thread_id;
    pthread_attr_t attr;
    pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
    pthread_create(&thread_id,&attr,start_run,NULL); //若attr为NULL, 则为默认属性
    pthread_attr_destroy(&attr);
    方法2.子线程退出前调用:pthread_detach()

  • 获取线程ID:

 pthread_t  pthread_self(void)

Windows篇

  • 创建:
LPDWORD lpThreadId = NULL;
HANDLE threadHandle = CreateThread(NULL, //属性
                                    0, //栈大小
                                    threadRoutine,//线程函数
                                    NULL, //函数传参
                                    0, //默认值, 表示线程立刻激活
                                    lpThreadId);//线程ID
  • 资源回收
(1).CloseHandle(HANDLE threadHandle):
    释放句柄可以是任何位置, 该函数是线程句柄引用计数减一, 减一之后线程不影响线程运行, 而是等线程返回后由操作系统回收.
(2).DWORD WaitForSingleObject(
                    HANDLE hObject, //句柄
                    DWORD dwMilliseconds //超时时间, 单位毫秒;INFINITE为无限时间(即阻塞回收),值为-1;
                );
  • 获取线程ID: GetCurrentThreadId()

你可能感兴趣的:(C/C++,线程,win,linux)