多線程-線程鎖-while循環

今天寫多線程遇到了幾個問題,導致程序一直無法正常運行:

  1. 多個線程共用一個函數的時候,,由於沒有用線程鎖,導致無法正常運行;
  2. 函數中有while循環,加入多線程之後,,由於沒有進行初始化互斥量,導致只有第一個線程起作用。

線程鎖之互斥鎖的使用:

  • 定義互斥量:pthread_mutex_t mutex;
  • 初始化互斥量:pthread_mutex_init(&mutex,NULL);
  • 上鎖:pthread_mutex_lock(&mutex);
  • 解鎖:pthread_mutex_unlock(&mutex);
  • 銷燬:pthread_mutex_destroy(&mutex);

下面是例子:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

#define THREADMAX 10

int sid[10];
pthread_t thread[THREADMAX];
pthread_mutex_t mut; //互斥鎖類型

void *thread1(void* a) //線程函數
{
    pthread_mutex_init(&mut,NULL);//用默認屬性初始化互斥鎖
    pthread_mutex_lock(&mut); //加鎖,用於對共享變量操作
    while(1)
    {
        int thread_id=*(int *)a;
        printf("thread_id: %d\n",thread_id);
        sleep(1);
    }
    pthread_mutex_unlock(&mut); //解鎖

}

void thread_create(void)
{
    /*創建線程*/
    int i=0;
    for (i=0;i<THREADMAX;i++){
        sid[i] = i;
        pthread_create(&thread[i], NULL, thread1, &sid[i]);
    }
}

void thread_wait(void)
{
	/*等待某進程結束*/
    int i=0;
    for (i=0;i<THREADMAX ;i++){
        pthread_join(thread[i],NULL);
    }
}

int main()
{
    thread_create();
    thread_wait();
    return 0;
}

發佈了34 篇原創文章 · 獲贊 11 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章