C语言多线程

94 阅读1分钟

创建

void* myfunc(void* args){
    for (int i=0;i<20;i++)
        printf("now: %d\n", i);
}
pthread_t th;
pthread_create(&th, NULL, myfunc, NULL);

运行时要加上-lpthread

等待执行

pthread_join(th, NULL);

pthread_mutex_t锁代码而不是锁变量,当执行到锁住的代码时,只有当代码未被锁住时才能往下运行,否则需要等待。

pthread_mutex_t lock;
pthread_mutex_lock(&lock);
// 需要锁住的代码
pthread_mutex_unlock(&lock);

注意:锁一般不放在循环里面,会拖慢速度

假共享(false sharing)

key

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

pthread_key_t key;
pthread_t thid1;
pthread_t thid2;

void* thread2(void* arg)
{
    printf("thread:%lu is running\n", pthread_self());
    
    int key_va = 3 ;

    pthread_setspecific(key, (void*)key_va);
    
    printf("thread:%lu return %d\n", pthread_self(), (int)pthread_getspecific(key));
}


void* thread1(void* arg)
{
    printf("thread:%lu is running\n", pthread_self());
    
    int key_va = 5;
    
    pthread_setspecific(key, (void*)key_va);

    pthread_create(&thid2, NULL, thread2, NULL);

    printf("thread:%lu return %d\n", pthread_self(), (int)pthread_getspecific(key));
}


int main()
{
    printf("main thread:%lu is running\n", pthread_self());

    pthread_key_create(&key, NULL);

    pthread_create(&thid1, NULL, thread1, NULL);

    pthread_join(thid1, NULL);
    pthread_join(thid2, NULL);

    int key_va = 1;
    pthread_setspecific(key, (void*)key_va);
    
    printf("thread:%lu return %d\n", pthread_self(), (int)pthread_getspecific(key));

    pthread_key_delete(key);
        
    printf("main thread exit\n");
    return 0;
}
nohup ./test > myout.txt 2>&1 &

注意:> 是把输出转向到指定的文件,是覆盖写
>> 是把输出附向到文件的后面,是追加写

使用> 命令时原命令的输出不会显示到命令行