线程与线程属性相关。

线程

线程创建

线程ID只有在它所属的进程上下文中才有意义。

1
#include<pthread.h>
2
int pthread_equal(pthread_t tid1, pthread_t tid2);
3
int pthread_self(void); //调用线程获取自身的线程ID
4
int pthread_create(pthread_t *restrict tidp,
5
    const pthread_attr_t *restrict attr,
6
    void *(*start_rtn)(void *), void *restrict arg);

新创建的线程ID会被设置为tidp指向的内存单元。attr参数用于定制各种不同的线程属性。新创建的线程从start_rtn函数的地址开始运行,该函数只有一个无类型指针参数arg。

每个线程都提供errno的副本。

1
#include "apue.h"
2
#include <pthread.h>
3
4
pthread_t ntid;
5
6
void printids(const char *s)
7
{
8
    pid_t      pid;
9
    pthread_t  tid;
10
11
    pid = getpid();
12
    tid = pthread_self();
13
    printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid,
14
      (unsigned int)tid, (unsigned int)tid);
15
}
16
17
void* thr_fn(void *arg)
18
{
19
    printids("new thread: ");
20
    return((void *)0);
21
}
22
23
int main(void)
24
{
25
    int     err;
26
    err = pthread_create(&ntid, NULL, thr_fn, NULL);
27
    if (err != 0)
28
        err_quit("can't create thread: %s\n", strerror(err));
29
    printids("main thread:");
30
    sleep(1);
31
    exit(0);
32
}

线程终止

1
void pthread_exit(void *rval_ptr);
2
int pthread_join(pthread_t thread, void **rval_ptr);

pthread_join调用线程将一直阻塞,直到指定线程调用pthread_exit,从启动例程中返回或者被取消。如果线程从它的启动例程返回,则rval_ptr包含返回码。如果线程被取消,rval_ptr指定的内存单元就设置为PTHREAD_CANCELED

1
#include "apue.h"
2
#include <pthread.h>
3
4
void *thr_fn1(void *arg)
5
{
6
    printf("thread 1 returning\n");
7
    return((void *)1);
8
}
9
10
void *thr_fn2(void *arg)
11
{
12
    printf("thread 2 exiting\n");
13
    pthread_exit((void *)2);
14
}
15
16
int main(void)
17
{
18
    int         err;
19
    pthread_t   tid1, tid2;
20
    void        *tret;
21
22
    err = pthread_create(&tid1, NULL, thr_fn1, NULL);
23
    if (err != 0)
24
        err_quit("can't create thread 1: %s\n", strerror(err));
25
    err = pthread_create(&tid2, NULL, thr_fn2, NULL);
26
    if (err != 0)
27
        err_quit("can't create thread 2: %s\n", strerror(err));
28
    err = pthread_join(tid1, &tret);
29
    if (err != 0)
30
        err_quit("can't join with thread 1: %s\n", strerror(err));
31
    printf("thread 1 exit code %d\n", (int)tret);
32
    err = pthread_join(tid2, &tret);
33
    if (err != 0)
34
        err_quit("can't join with thread 2: %s\n", strerror(err));
35
    printf("thread 2 exit code %d\n", (int)tret);
36
    exit(0);
37
}
38
39
$ ./a.out
40
thread 1 returning
41
thread 2 exiting
42
thread 1 exit code 1
43
thread 2 exit code 2

线程可以调用pthread_cancel函数来请求取消同一进程的其他线程。但是线程可以选择忽略取消或者控制如何被取消。pthread_cancel并不等待线程终止,它仅仅提出请求。

1
int pthread_cancel(pthread_t tid);
2
//线程清理处理程序
3
void pthread_cleanup_push(void (*rtn)(void *), void *arg);
4
void pthread_cleanup_pop(int execute);
5
//分离线程
6
int pthread_detach(pthread_t tid);

线程同步

当一个线程可以修改的变量,其他线程也可以读取或修改该变量时,就会存在访问数据不一致的问题。

当两个或多个线程试图同时在同一时间修改同一变量时,也存在数据访问不一致问题。

互斥量

互斥量使用pthread_mutex_t数据类型表示,在使用互斥量前,必须首先对它进行初始化

  • 可以把它设置为常量PTHREAD_MUTEX_INITIALIZER(只适用于静态分配的互斥量)。
  • 也可以调用pthread_mutex_init函数初始化。在释放内存前需要调用pthread_mutex_destroy
1
#include<pthread.h>
2
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
3
        const pthread_mutexattr_t *restrict attr);
4
int pthread_mutex_destroy(pthread_mutex_t *mutex);

调用pthread_mutex_lock对互斥量进行上锁后,调用线程将阻塞直到互斥量被解锁🔓。如果不希望线程被阻塞,可以使用pthread_mutex_trylock尝试对线程加锁,如果不能锁住互斥量,则返回EBUSY

1
#include<pthread.h>
2
int pthread_mutex_lock(pthread_mutex_t *mutex);
3
int pthread_mutex_trylock(pthread_mutex_t *mutex);
4
int pthread_mutex_unlock(pthread_mutex_t *mutex);
1
#include <stdlib.h>
2
#include <pthread.h>
3
4
struct foo {
5
    int             f_count;
6
    pthread_mutex_t f_lock;
7
    int             f_id;
8
    /* ... more stuff here ... */
9
};
10
11
struct foo * foo_alloc(int id) /* allocate the object */
12
{
13
    struct foo *fp;
14
15
    if ((fp = malloc(sizeof(struct foo))) != NULL) {
16
        fp->f_count = 1;
17
        fp->f_id = id;
18
        if (pthread_mutex_init(&fp->f_lock, NULL) != 0) {
19
            free(fp);
20
            return(NULL);
21
        }
22
        /* ... continue initialization ... */
23
    }
24
    return(fp);
25
}
26
27
void foo_hold(struct foo *fp) /* add a reference to the object */
28
{
29
    pthread_mutex_lock(&fp->f_lock);
30
    fp->f_count++;
31
    pthread_mutex_unlock(&fp->f_lock);
32
}
33
34
void foo_rele(struct foo *fp) /* release a reference to the object */
35
{
36
    pthread_mutex_lock(&fp->f_lock);
37
    if (--fp->f_count == 0) { /* last reference */
38
        pthread_mutex_unlock(&fp->f_lock);
39
        pthread_mutex_destroy(&fp->f_lock);
40
        free(fp);
41
    } else {
42
        pthread_mutex_unlock(&fp->f_lock);
43
    }
44
}
死锁
  • 如果线程试图对同一个互斥量加锁两次,那么它自身就会陷入死锁状态。
  • 如果一个线程试图锁住另一个线程以相反的顺序锁住的互斥量时,会陷入死锁状态。
1
#include <stdlib.h>
2
#include <pthread.h>
3
4
#define NHASH 29
5
#define HASH(id) (((unsigned long)id)%NHASH)
6
7
struct foo *fh[NHASH];
8
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
9
10
struct foo {
11
    int             f_count; /* protected by hashlock */
12
    pthread_mutex_t f_lock;
13
    struct foo     *f_next; /* protected by hashlock */
14
    int             f_id;
15
    /* ... more stuff here ... */
16
};
17
18
struct foo *foo_alloc(int id) /* allocate the object */
19
{
20
    struct foo  *fp;
21
    int         idx;
22
23
    if ((fp = malloc(sizeof(struct foo))) != NULL) {
24
        fp->f_count = 1;
25
        fp->f_id = id;
26
        if (pthread_mutex_init(&fp->f_lock, NULL) != 0) {
27
            free(fp);
28
            return(NULL);
29
        }
30
        idx = HASH(id);
31
        pthread_mutex_lock(&hashlock);
32
        fp->f_next = fh[idx];
33
        fh[idx] = fp;
34
        pthread_mutex_lock(&fp->f_lock);
35
        pthread_mutex_unlock(&hashlock);
36
        /* ... continue initialization ... */
37
        pthread_mutex_unlock(&fp->f_lock);
38
    }
39
    return(fp);
40
}
41
42
void foo_hold(struct foo *fp) /* add a reference to the object */
43
{
44
    pthread_mutex_lock(&hashlock);
45
    fp->f_count++;
46
    pthread_mutex_unlock(&hashlock);
47
}
48
49
struct foo *foo_find(int id) /* find a existing object */
50
{
51
    struct foo  *fp;
52
53
    pthread_mutex_lock(&hashlock);
54
    for (fp = fh[HASH(idx)]; fp != NULL; fp = fp->f_next) {
55
        if (fp->f_id == id) {
56
            fp->f_count++;
57
            break;
58
        }
59
    }
60
    pthread_mutex_unlock(&hashlock);
61
    return(fp);
62
}
63
64
void foo_rele(struct foo *fp) /* release a reference to the object */
65
{
66
    struct foo  *tfp;
67
    int         idx;
68
69
    pthread_mutex_lock(&hashlock);
70
    if (--fp->f_count == 0) { /* last reference, remove from list */
71
        idx = HASH(fp->f_id);
72
        tfp = fh[idx];
73
        if (tfp == fp) {
74
            fh[idx] = fp->f_next;
75
        } else {
76
            while (tfp->f_next != fp)
77
                tfp = tfp->f_next;
78
            tfp->f_next = fp->f_next;
79
        }
80
        pthread_mutex_unlock(&hashlock);
81
        pthread_mutex_destroy(&fp->f_lock);
82
        free(fp);
83
    } else {
84
        pthread_mutex_unlock(&hashlock);
85
    }
86
}

pthread_mutex_timedlock互斥量原语允许绑定线程阻塞时间。

1
#include<pthread.h>
2
#include<time.h>
3
int pthread_mutex_timedlock(pthread_mutex_t *restrict mutex,
4
        const struct timespec *restrict tsptr);
1
#include "apue.h"
2
#include <pthread.h>
3
4
int main(void)
5
{
6
    int err;
7
    struct timespec tout;
8
    struct tm *tmp;
9
    char buf[64];
10
    pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
11
12
    pthread_mutex_lock(&lock);
13
    printf("mutex is locked\n");
14
    clock_gettime(CLOCK_REALTIME, &tout);
15
    tmp = localtime(&tout.tv_sec);
16
    strftime(buf,sizeof(buf),"%r",tmp);
17
    printf("current time is %s\n", buf);
18
    tout.tv_sec += 10;
19
    err = pthread_mutex_timedlock(&lock, &tout);
20
    clock_gettime(CLOCK_REALTIME, &tout);
21
    tmp = localtime(&tout.tv_sec);
22
    strftime(buf,sizeof(buf),"%r",tmp);
23
    printf("the time is now %s\n", buf);
24
    if(err == 0)
25
        printf("mutex locked again!\n");
26
    else
27
        printf("can't lock mvtex again:%s\n",strerror(err));
28
    exit(0);
29
}

读写锁

当读写锁是写加锁状态时,在这个锁被解锁前,所有试图对这个锁加锁的线程都会被阻塞。

当读写锁是读加锁状态时,所有试图以读模式对它进行加锁的线程都可以得到访问权。但是任何希望以写模式对此锁进行加锁的线程都会阻塞,知道所有的线程释放它们的读锁为止。

当读写锁处于读模式锁住状态,而这时有一个线程试图以写模式获取锁时,读写锁通常会阻塞随后的读模式锁请求,这样可避免读模式锁长期占用,而等待的写模式锁请求一直得不到满足。

PTHREAD_RWLOCK_INITIALIZER常量可以对静态分配的读写锁进行初始化。

1
#include<pthread.h>
2
int pthread_rwlock_init(pthread_rwlock_t *restricy rwlock,
3
        const pthread_rwlockattr_t *restrict attr);
4
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
5
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
6
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
7
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
8
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
9
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
10
int pthread_rwlock_timedrdlock(pthread_rwlock_t *restrict rwlock,
11
        const struct timespec *restrict tsptr);
12
int pthread_rwlock_timedwrlock(pthread_rwlock_t *restrict rwlock,
13
        const struct timespec *restrict tsptr);
1
#include <stdlib.h>
2
#include <pthread.h>
3
4
struct job {
5
    struct job *j_next;
6
    struct job *j_prev;
7
    pthread_t   j_id;   /* tells which thread handles this job */
8
    /* ... more stuff here ... */
9
};
10
11
struct queue {
12
    struct job      *q_head;
13
    struct job      *q_tail;
14
    pthread_rwlock_t q_lock;
15
};
16
17
/*
18
* Initialize a queue.
19
*/
20
int queue_init(struct queue *qp)
21
{
22
    int err;
23
24
    qp->q_head = NULL;
25
    qp->q_tail = NULL;
26
    err = pthread_rwlock_init(&qp->q_lock, NULL);
27
    if (err != 0)
28
        return(err);
29
    /* ... continue initialization ... */
30
    return(0);
31
}
32
33
/*
34
 * Insert a job at the head of the queue.
35
 */
36
void job_insert(struct queue *qp, struct job *jp)
37
{
38
    pthread_rwlock_wrlock(&qp->q_lock);
39
    jp->j_next = qp->q_head;
40
    jp->j_prev = NULL;
41
    if (qp->q_head != NULL)
42
        qp->q_head->j_prev = jp;
43
    else
44
        qp->q_tail = jp;      /* list was empty */
45
    qp->q_head = jp;
46
    pthread_rwlock_unlock(&qp->q_lock);
47
}
48
49
/*
50
 * Append a job on the tail of the queue.
51
 */
52
void job_append(struct queue *qp, struct job *jp)
53
{
54
    pthread_rwlock_wrlock(&qp->q_lock);
55
    jp->j_next = NULL;
56
    jp->j_prev = qp->q_tail;
57
    if (qp->q_tail != NULL)
58
        qp->q_tail->j_next = jp;
59
    else
60
        qp->q_head = jp;   /* list was empty */
61
    qp->q_tail = jp;
62
    pthread_rwlock_unlock(&qp->q_lock);
63
}
64
65
/*
66
 * Remove the given job from a queue.
67
 */
68
void job_remove(struct queue *qp, struct job *jp)
69
{
70
    pthread_rwlock_wrlock(&qp->q_lock);
71
    if (jp == qp->q_head) {
72
        qp->q_head = jp->j_next;
73
        if (qp->q_tail == jp)
74
            qp->q_tail = NULL;
75
    } else if (jp == qp->q_tail) {
76
        qp->q_tail = jp->j_prev;
77
        if (qp->q_head == jp)
78
            qp->q_head = NULL;
79
    } else {
80
        jp->j_prev->j_next = jp->j_next;
81
        jp->j_next->j_prev = jp->j_prev;
82
    }
83
    pthread_rwlock_unlock(&qp->q_lock);
84
}
85
/*
86
 * Find a job for the given thread ID.
87
 */
88
struct job * job_find(struct queue *qp, pthread_t id)
89
{
90
    struct job *jp;
91
92
    if (pthread_rwlock_rdlock(&qp->q_lock) != 0)
93
        return(NULL);
94
95
    for (jp = qp->q_head; jp != NULL; jp = jp->j_next)
96
         if (pthread_equal(jp->j_id, id))
97
             break;
98
99
    pthread_rwlock_unlock(&qp->q_lock);
100
    return(jp);
101
}

条件变量

条件变量与互斥量一起使用时,允许线程以无竞争的方式等待特定的条件发生。

条件本身是由互斥量保护的。线程在改变条件状态之前必须首先锁住互斥量。其他线程在获得互斥量之前不会察觉到这种改变,因为互斥量必须在锁定以后才能计算条件。

常量PTHREAD_COND_INITIALIZER赋给静态分配的条件变量。

1
#include<pthread.h>
2
int pthread_cond_init(pthread_cond_t *restrict cond,
3
        const pthread_condattr_t *restrict attr);
4
int pthread_cond_destroy(pthread_cond_t *cond);
5
int pthread_cond_wait(pthread_cond_t *restrict cond,
6
        pthread_mutex_t *restrict mutex);
7
int pthread_cond_timedwait(pthread_cond_t *restrict cond,
8
        pthread_mutex_t *restrict mutex,
9
        const struct timespec *restrict tsptr);
10
int pthread_cond_signal(pthread_cond_t *cond);
11
int pthread_cond_broadcast(pthread_cond_t *cond);
1
#include <pthread.h>
2
3
struct msg {
4
    struct msg *m_next;
5
    /* ... more stuff here ... */
6
};
7
struct msg *workq;
8
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
9
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
10
11
void process_msg(void)
12
{
13
    struct msg *mp;
14
15
    for (;;) {
16
        pthread_mutex_lock(&qlock);
17
        while (workq == NULL)
18
            pthread_cond_wait(&qready, &qlock);
19
        mp = workq;
20
        workq = mp->m_next;
21
        pthread_mutex_unlock(&qlock);
22
        /* now process the message mp */
23
    }
24
}
25
26
void enqueue_msg(struct msg *mp)
27
{
28
    pthread_mutex_lock(&qlock);
29
    mp->m_next = workq;
30
    workq = mp;
31
    pthread_mutex_unlock(&qlock);
32
    pthread_cond_signal(&qready);
33
}

自旋锁

自旋锁不是通过休眠使进程阻塞,而是在获取锁之前一直处于忙等待(自旋)阻塞状态。

自旋锁通常作为底层原语用于实现其他类型的锁。在用户层,自旋锁并不是非常有用。

1
#include<pthread.h>
2
int pthread_spin_init(pthread_spinlock_t *lock, int pshared);
3
int pthread_spin_destroy(pthread_spinlock_t *lock);
4
int pthread_spin_lock(pthread_spinlock_t *lock);
5
int pthread_spin_trylock(pthread_spinlock_t *lock);
6
int pthread_spin_unlock(pthread_spinlock_t *lock);

屏障

屏障(barrier)是用户协调多个线程并行的同步机制。

1
#include<pthread.h>
2
int pthread_barrier_init(pthread_barrier_t *restrict barrier,
3
        const pthread_barrierattr_t *restrict attr,
4
        unsigned int count);
5
int pthread_barrier_destroy(pthread_barrier_t *barrier);
6
int pthread_barrier_wait(pthread_barrier_t *barrier);
1
#include "apue.h"
2
#include <pthread.h>
3
#include <limits.h>
4
#include <sys/time.h>
5
6
#define NTHR 8
7
#define NUMNUM 8000000L
8
#define TNUM (NUMNUM/NTHR)
9
10
long nums[NUMNUM];
11
long snums[NUMNUM];
12
13
pthread_barrier_t b;
14
15
#ifdef SOLARIS
16
#define heapsort qsort
17
#else
18
extern int heapsort(void *, size_t, size_t, 
19
                int (*)(const void *, const void *));
20
#endif
21
22
int complong(const void *arg1, const void *arg2)
23
{
24
    long l1 = *(long *)arg1;
25
    long l2 = *(long *)arg2;
26
27
    if(l1 == l2)
28
        return 0;
29
    else if(l1 < l2)
30
        return -1;
31
    else
32
        return 1;
33
}
34
35
void *thr_fn(void *arg)
36
{
37
    long idx = (long)arg;
38
39
    heapsort(&nums[idx], TNUM, sizeof(long), complong);
40
    pthread_barrier_wait(&b);
41
    /* ... */
42
    return ((void *)0);
43
}
44
45
void merge()
46
{
47
    long idx[NTHR];
48
    long i, minidx, sidx, num;
49
50
    for(i = 0; i<NTHR; i++)
51
        idx[i] = i * TNUM;
52
    for(sidx = 0; sidx < NUMNUM; sidx++)
53
    {
54
        num = LONG_MAX;
55
        for(i = 0; i < NTHR; i++)
56
        {
57
            if((idx[i] < (i+1)*TNUM) && (nums[idx[i]] < num))
58
            {
59
                num = nums[idx[i]];
60
                minidx = i;
61
            }
62
        }
63
        snums[sidx] = nums[idx[minidx]];
64
        idx[minidx]++;
65
    }
66
}
67
68
int main()
69
{
70
    unsigned long       i;
71
    struct timeval      start, end;
72
    long long           startusec, endusec;
73
    double              elapsed;
74
    int                 err;
75
    pthread_t           tid;
76
77
    srandom(1);
78
    for(i = 0; i < NUMNUM; i++)
79
        nums[i] = random();
80
81
    gettimeeeofday(&start, NULL);
82
    pthread_barrier_init(&b, NULL, NTHR+1);
83
    for(i = 0; i < NTHR; i++)
84
    {
85
        err = pthread_create(&tid, NULL, thr_fn, (void *)(i * TNUM));
86
        if(err != 0)
87
            err_exit(err, "can't create thread");
88
    }
89
    pthread_barrier_wait(&b);
90
    merge();
91
    gettimeofday(&end, NULL);
92
93
    startusec = start.tv_sec * 1000000 + start.tv_usec;
94
    endusec = end.tv_sec * 1000000 + end.tv_usec;
95
    elapsed = (double)(endusec - startusec) / 1000000.0;
96
    printf("sort took %.4f seconds\n", elapsed);
97
    for(i = 0; i < NUMNUM; i++)
98
        printf("%ld\n", snums[i]);
99
    exit(0);
100
}

线程控制

线程属性

1
#include <pthread.h>
2
3
int pthread_attr_init(pthread_attr_t *attr);
4
int pthread_attr_destroy(pthread_attr_t   *attr);
5
6
int pthread_attr_getdetachstate(const pthread_attr_t *restrict attr,
7
            int *detachstate);
8
//PTHREAD_CREATE_DETACHED, PTHREAD_CREATE_JOINABLE
9
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);
10
11
int pthread_attr_getstack(const pthread_attr_t *restrict attr,
12
            void **restrict stackaddr, size_t *restrict stacksize);
13
int pthread_attr_setstack(const pthread_attr_t *attr,
14
            void *stackaddr, size_t* stacksize);
15
16
int pthread_attr_getstacksize(const pthread_attr_t *restrict attr,
17
            size_t *restrict stacksize);
18
int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize);
19
20
int pthread_attr_getguardsize(const pthread_attr_t *restrict attr,
21
            size_t *restrict guardsize);
22
int pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize);
名称 描述
detachstate 线程分离状态属性
guardsize 线程栈末尾的警戒缓冲区大小(字节数)
stackaddr 线程栈的最低地址
stacksize 线程栈的最小长度(字节数)
1
#include "apue.h"
2
#include <pthread.h>
3
4
int makethread(void *(*fn)(void *), void *arg)
5
{
6
    int             err;
7
    pthread_t       tid;
8
    pthread_attr_t  attr;
9
10
    err = pthread_attr_init(&attr);
11
    if (err != 0)
12
        return(err);
13
    err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
14
    if (err == 0)
15
        err = pthread_create(&tid, &attr, fn, arg);
16
    pthread_attr_destroy(&attr);
17
    return(err);
18
}

同步属性

互斥量属性

在进程中,多个线程可以访问同一个同步对象,这是默认行为,这种情况下,进程共享互斥量属性需设置为PTHREAD_PROCESS_PRIVATE

如果进行共享互斥量属性设置为PTHREAD_PROCESS_SHARED,从多个进程彼此之间共享的内存数据块中分配的互斥量就可以用于这些进程的同步。

互斥量健壮属性与在多个进程间共享的互斥量有关。当持有互斥量的进程终止时,互斥量处于锁定状态,恢复起来很困难,其他阻塞这个锁的进程将会一直阻塞下去。

健壮属性取值:

  • PTHREAD_MUTEX_STALLED默认值,持有互斥量的进程终止时不需要采取特别的动作。
  • PTHREAD_MUTEX_ROBUST,该属性时调用线程获取pthread_mutex_lock锁时,该锁被另一个进程持有,但该进程终止并没有对锁进行解释时,此线程阻塞,从pthread_mutex_lock返回值为EOWNERDEAD而不是0。

如果应用状态无法恢复,在线程对互斥量解锁以后,该互斥量将处于永久不可用状态。pthread_mutex_consistent指明与该互斥量相关的状态在互斥量解锁之前是一致的。

1
#include <pthread.h>
2
3
int pthread_mutexattr_init(pthread_mutexattr_t *attr);
4
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr);
5
//进程共享属性
6
int pthread_mutexattr_getpshared(const pthread_mutexattr_t *restrict 
7
                attr,int *restrict pshared);
8
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr,
9
                int pshared);
10
//健壮属性
11
int pthread_mutexattr_getrobust(const pthread_mutexattr_t *restrict 
12
                attr,int *restrict robust);
13
int pthread_mutexattr_getrobust(pthread_mutexattr_t *restrict attr,
14
                int robust);
15
16
int pthread_mutex_consistent(pthread_mutex_t *mutex);
17
//类型属性
18
int pthread_mutexattr_gettype(const pthread_mutexattr_t *restrict 
19
                attr, int *restrict type);
20
int pthread_mutexattr_settype(pthread_mutexattr_ *attr, int type);
互斥量类型属性 没有解锁时重新加锁? 不占用锁时解锁? 在已解锁时解锁?
PTHREAD_MUTEX_NORMAL 死锁 未定义 未定义
PTHREAD_MUTEX_ERRORCHECK 返回错误 返回错误 返回错误
PTHREAD_MUTEX_RECURSIVE 允许 返回错误 返回错误
PTHREAD_MUTEX_DDDEFAULT 未定义 未定义 未定义

读写锁属性

读写锁支持的唯一属性是进程共享属性。与互斥量进程共享属性一样。

1
#include <pthread.h>
2
3
int pthread_rwlockattr_init(pthread_rwlockattr_t *attr);
4
int pthread_rwlockattr_destroy(pthread_rwlockattr_t *attr);
5
6
int pthread_rwlockattr_getpshared(const pthread_rwlockattr_t *
7
                    restrict attr,int *restrict pshared);
8
int pthread_rwlockattr_setpshared(pthread_rwlockattr_t *attr,
9
                    int pshared);

条件变量属性

条件变量支持两个属性:进程共享属性和时钟属性。

1
#include <pthread.h>
2
3
int pthread_condattr_init(pthread_condattr_t *attr);
4
int pthread_condattr_destroy(pthread_condattr_t *attr);
5
6
int pthread_condattr_getpshared(const pthread_condattr_t *
7
                    restrict attr,int *restrict pshared);
8
int pthread_condattr_setpshared(pthread_condattr_t *attr,
9
                    int pshared);
10
11
int pthread_condattr_getclock(const pthread_condattr_t *
12
            restrict attr,clockid_t *restrict clock_id);
13
int pthread_condattr_setclock(pthread_condattr_t *attr,
14
            clockid_t clock_id);

屏障属性

目前屏障属性只有进程共享属性。

1
#include<pthread.h>
2
int pthread_barrierattr_init(pthread_barrierattr_t *attr);
3
int pthread_barrierattr_destroy(pthread_barrierattr_t *attr);
4
int pthread_barrierattr_getpshared(const 
5
            pthread_barrierattr_t *restrict attr, 
6
            int *restrict pshared);
7
int pthread_barrierattr_setpshared(pthread_barrierattr_t 
8
            *attr,int pshared);

重入

一个函数在相同的时间点可以被多个线程安全地调用,就称该函数是线程安全的。

线程特定数据

线程特定数据(thread-specific data)也称为线程私有数据(thread-private data),是存储和查询某个特定线程相关数据的一种机制。

线程私有数据是关于每个线程可以访问它自己单独的数据副本,而不需要担心与其它线程的同步访问问题。

一个进程中的所有线程都可以访问这个进程的整个地址空间。除了使用寄存器以外,一个线程没有办法阻止另一个线程访问它的数据。线程特定数据也不例外。但管理线程特定数据的函数可以提高线程间的数据独立性,使线程不容易访问到其它线程的特定数据。

1
#include <pthread.h>
2
3
int pthread_key_create(pthread_key_t *keyp, void (*destructor)(void *));
4
int pthread_key_delete(pthread_key_t *key);
5
6
pthread_once_t initflag = PTHREAD_ONCE_INIT;
7
int pthread_once(pthread_once_t *initflag, void (*initfn)(void));
8
9
void *pthread_getspecific(pthread_key_t key);
10
int pthread_setspecific(pthread_key_t key, const void *value);
1
#include <limits.h>
2
#include <string.h>
3
#include <pthread.h>
4
#include <stdlib.h>
5
6
static pthread_key_t key;
7
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
8
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
9
10
extern char **environ;
11
12
static void thread_init(void)
13
{
14
    pthread_key_create(&key, free);
15
}
16
17
char *getenv(const char *name)
18
{
19
    int     i, len;
20
    char    *envbuf;
21
22
    pthread_once(&init_done, thread_init);
23
    pthread_mutex_lock(&env_mutex);
24
    envbuf = (char *)pthread_getspecific(key);
25
    if (envbuf == NULL) {
26
        envbuf = malloc(ARG_MAX);
27
        if (envbuf == NULL) {
28
            pthread_mutex_unlock(&env_mutex);
29
            return(NULL);
30
        }
31
        pthread_setspecific(key, envbuf);
32
    }
33
    len = strlen(name);
34
    for (i = 0; environ[i] != NULL; i++) {
35
        if ((strncmp(name, environ[i], len) == 0) &&
36
          (environ[i][len] == '=')) {
37
            strcpy(envbuf, &environ[i][len+1]);
38
            pthread_mutex_unlock(&env_mutex);
39
            return(envbuf);
40
        }
41
    }
42
    pthread_mutex_unlock(&env_mutex);
43
    return(NULL);
44
}

取消选项

1
#include <pthread.h>
2
3
int pthread_setcancelstate(int state, int *oldstate);
4
void pthread_testcancel(void);
5
int pthread_setcanceltype(int type, int *oldtype);

线程和信号

1
#include <signal.h>
2
3
int pthread_sigmask(int how, const sigset_t *restrict set,
4
                 sigset_t *restrict oset);
5
int sigwait(const sigset_t *restrict set, 
6
                int *restrict signop);
7
int pthread_kill(pthread_t thread, int signo);
1
#include "apue.h"
2
#include <pthread.h>
3
4
int         quitflag;   /* set nonzero by thread */
5
sigset_t    mask;
6
7
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
8
pthread_cond_t wait = PTHREAD_COND_INITIALIZER;
9
10
void *thr_fn(void *arg)
11
{
12
    int err, signo;
13
14
    for (;;) {
15
        err = sigwait(&mask, &signo);
16
        if (err != 0)
17
            err_exit(err, "sigwait failed");
18
        switch (signo) {
19
        case SIGINT:
20
            printf("\ninterrupt\n");
21
            break;
22
23
        case SIGQUIT:
24
            pthread_mutex_lock(&lock);
25
            quitflag = 1;
26
            pthread_mutex_unlock(&lock);
27
            pthread_cond_signal(&wait);
28
            return(0);
29
30
        default:
31
            printf("unexpected signal %d\n", signo);
32
            exit(1);
33
        }
34
    }
35
}
36
int main(void)
37
{
38
    int         err;
39
    sigset_t    oldmask;
40
    pthread_t   tid;
41
42
    sigemptyset(&mask);
43
    sigaddset(&mask, SIGINT);
44
    sigaddset(&mask, SIGQUIT);
45
    if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0)
46
        err_exit(err, "SIG_BLOCK error");
47
48
    err = pthread_create(&tid, NULL, thr_fn, 0);
49
    if (err != 0)
50
        err_exit(err, "can't create thread");
51
52
    pthread_mutex_lock(&lock);
53
    while (quitflag == 0)
54
        pthread_cond_wait(&wait, &lock);
55
    pthread_mutex_unlock(&lock);
56
57
    /* SIGQUIT has been caught and is now blocked; do whatever */
58
    quitflag = 0;
59
60
    /* reset signal mask which unblocks SIGQUIT */
61
    if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
62
        err_sys("SIG_SETMASK error");
63
    exit(0);
64
}

线程和fork

1
#include <pthread.h>
2
int pthread_atfork(void (*prepare)(void), 
3
        void (*parent)(void), void (*child)(void));
1
#include "apue.h"
2
#include <pthread.h>
3
4
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
5
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
6
7
void prepare(void)
8
{
9
    printf("preparing locks...\n");
10
    pthread_mutex_lock(&lock1);
11
    pthread_mutex_lock(&lock2);
12
}
13
void parent(void)
14
{
15
    printf("parent unlocking locks...\n");
16
    pthread_mutex_unlock(&lock1);
17
    pthread_mutex_unlock(&lock2);
18
}
19
20
void child(void)
21
{
22
    printf("child unlocking locks...\n");
23
    pthread_mutex_unlock(&lock1);
24
    pthread_mutex_unlock(&lock2);
25
}
26
27
void *thr_fn(void *arg)
28
{
29
    printf("thread started...\n");
30
    pause();
31
    return(0);
32
}
33
34
int main(void)
35
{
36
    int         err;
37
    pid_t       pid;
38
    pthread_t   tid;
39
40
#if defined(BSD) || defined(MACOS)
41
    printf("pthread_atfork is unsupported\n");
42
#else
43
    if ((err = pthread_atfork(prepare, parent, child)) != 0)
44
        err_exit(err, "can't install fork handlers");
45
    err = pthread_create(&tid, NULL, thr_fn, 0);
46
    if (err != 0)
47
        err_exit(err, "can't create thread");
48
    sleep(2);
49
    printf("parent about to fork...\n");
50
    if ((pid = fork()) < 0)
51
        err_quit("fork failed");
52
    else if (pid == 0) /* child */
53
        printf("child returned from fork\n");
54
    else        /* parent */
55
        printf("parent returned from fork\n");
56
#endif
57
    exit(0);
58
}

线程和I/O