Linux multithreaded programming


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

void *routine(void *num){
    printf("this is thread:%d\n",*(int*)num);
    return NULL;
}

int main(){
    const int n=20;
    pthread_t pids[n];
    int nums[n];
    int i;
    for(i=0;i<n;++i)nums[i]=i;
    for(i=0;i<n;++i){
        pthread_create(pids+i,NULL,routine,nums+i);   
    }
    while(1);//if we dont wait here,the main process may termiate before n threds finish
    return 0;

}

在这里插入图片描述

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

void *thread_func(void *arg) { return (void*)42; }
int main() {
    pthread_t tid;
    void *retval;
    pthread_create(&tid, NULL, thread_func, NULL);
    pthread_join(tid, &retval);
    printf("Thread returned %ld\n", (long)retval); // Output: 42
    return 0;
}

在这里插入图片描述


1. Thread Management

1.1 pthread_create()

Purpose: Create a new thread.
Syntax:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);

Parameters:
thread: Pointer to store the thread ID.
attr: Thread attributes (use NULL for defaults).
start_routine: Function the thread will execute.
arg: Argument passed to start_routine.
Return: 0 on success, error code on failure.
Example:

void *print_message(void *msg) {
    printf("%s\n", (char *)msg);
    return NULL;
}
int main() {
    pthread_t tid;
    char *msg = "Hello from thread!";
    pthread_create(&tid, NULL, print_message, msg);
    pthread_join(tid, NULL); // Wait for the thread
    return 0;
}

1.2 pthread_exit()

Purpose: Terminate the calling thread.
Syntax:

void pthread_exit(void *retval);

Parameters:
retval: Return value accessible via pthread_join().
Example:

void *thread_func(void *arg) {
    printf("Exiting thread\n");
    pthread_exit(NULL);
}

1.3 pthread_join()

Purpose: Wait for a thread to terminate and retrieve its exit status.
Syntax:

int pthread_join(pthread_t thread, void **retval);

Parameters:
thread: Thread ID to wait for.
retval: Stores the exit status of the thread.
Example:

void *thread_func(void *arg) { return (void*)42; }
int main() {
    pthread_t tid;
    void *retval;
    pthread_create(&tid, NULL, thread_func, NULL);
    pthread_join(tid, &retval);
    printf("Thread returned %ld\n", (long)retval); // Output: 42
    return 0;
}

1.4 pthread_detach()

Purpose: Mark a thread as detached (resources automatically released on termination).
Syntax:

int pthread_detach(pthread_t thread);

Example:

pthread_t tid;
pthread_create(&tid, NULL, thread_func, NULL);
pthread_detach(tid); // No need to join later

1.5 pthread_self(), pthread_equal()

Purpose: Get the thread ID of the current thread or compare two thread IDs.
Syntax:

pthread_t pthread_self(void);
int pthread_equal(pthread_t t1, pthread_t t2);

Example:

if (pthread_equal(pthread_self(), tid)) {
    printf("This is the main thread\n");
}

2. Synchronization

2.1 Mutexes

Purpose: Prevent race conditions by locking access to shared resources.
Functions:
pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
pthread_mutex_destroy(pthread_mutex_t *mutex)
pthread_mutex_lock(pthread_mutex_t *mutex)
pthread_mutex_unlock(pthread_mutex_t *mutex)
pthread_mutex_trylock(pthread_mutex_t *mutex)
Example:

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // Static initialization
void *thread_func(void *arg) {
    pthread_mutex_lock(&mutex);
    // Critical section
    pthread_mutex_unlock(&mutex);
    return NULL;
}

2.2 Condition Variables

Purpose: Allow threads to wait for specific conditions.
Functions:
pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) (atomically unlocks mutex and waits)
pthread_cond_signal(pthread_cond_t *cond) (wake one thread)
pthread_cond_broadcast(pthread_cond_t *cond) (wake all threads)
pthread_cond_destroy(pthread_cond_t *cond)
Example:

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *consumer(void *arg) {
    pthread_mutex_lock(&mutex);
    while (data_available == 0) {
        pthread_cond_wait(&cond, &mutex); // Releases mutex while waiting
    }
    // Consume data
    pthread_mutex_unlock(&mutex);
    return NULL;
}

2.3 Read-Write Locks

Purpose: Allow multiple readers or a single writer.
Functions:
pthread_rwlock_init()
pthread_rwlock_rdlock()
pthread_rwlock_wrlock()
pthread_rwlock_unlock()
Example:

pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
// Reader thread:
pthread_rwlock_rdlock(&rwlock);
// Read data
pthread_rwlock_unlock(&rwlock);
// Writer thread:
pthread_rwlock_wrlock(&rwlock);
// Modify data
pthread_rwlock_unlock(&rwlock);

3. Thread Attributes

Customize thread behavior (stack size, detach state, etc.):

pthread_attr_t attr;
pthread_attr_init(&attr); // Initialize with defaults
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); // Detached thread
pthread_attr_setstacksize(&attr, 1024*1024); // 1MB stack
pthread_create(&tid, &attr, thread_func, NULL);
pthread_attr_destroy(&attr); // Cleanup

4. Thread Cancellation

4.1 pthread_cancel()

Purpose: Request cancellation of another thread.
Syntax:

int pthread_cancel(pthread_t thread);

Example:

pthread_cancel(tid); // Send cancellation request
4.2 pthread_setcancelstate()

Purpose: Enable/disable cancellation.
Example:

pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); // Disable cancellation

5. Thread-Specific Data

5.1 pthread_key_create()

Purpose: Create a key for thread-specific data.
Syntax:

int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));

Example:

pthread_key_t key;
pthread_key_create(&key, NULL); // No destructor
pthread_setspecific(key, (void*)42); // Set data for current thread
void *data = pthread_getspecific(key); // Get data (42)

6. Other Functions

ponce_t and pthread_once(): Ensure a function is called once.

pthread_once_t once_control = PTHREAD_ONCE_INIT;
void init_once() { printf("Initialized once\n"); }
pthread_once(&once_control, init_once);

Barriers: Synchronize multiple threads at a point.

pthread_barrier_t barrier;
pthread_barrier_init(&barrier, NULL, 3); // Wait for 3 threads
pthread_barrier_wait(&barrier); // Blocks until all 3 threads reach here

Important Notes

• Always check return values for errors.
• Use perror() or strerror() to decode error codes.
• Avoid using exit() in threads; use pthread_exit() instead.
• Shared data requires synchronization (mutexes, condition variables).


This covers the most critical pthread functions. For deeper exploration, refer to the man pages (e.g., man pthread_create) or the POSIX specification.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值