相关文章推荐
小眼睛的鼠标垫  ·  nginx ...·  1 年前    · 
粗眉毛的枇杷  ·  Linux ...·  1 年前    · 
fp = fopen(filename, "r" ); if (fp == NULL ) { printf ( "Cannot open file %s\n" , filename); pthread_exit( NULL ); // 获取文件锁 flockfile(fp); while (fgets(buffer, sizeof (buffer), fp) != NULL ) { printf ( "%s" , buffer); // 释放文件锁 funlockfile(fp); fclose(fp); pthread_exit( NULL ); int main ( int argc, char * argv[]) { pthread_t threads[ 4 ]; int rc, i; for (i = 0 ; i < 4 ; i++) { rc = pthread_create(&threads[i], NULL , read_file, argv[ 1 ]); if (rc) { printf ( "Error: return code from pthread_create() is %d\n" , rc); return 1 ; // 等待所有线程完成 for (i = 0 ; i < 4 ; i++) { pthread_join(threads[i], NULL ); return 0 ;

在上面的示例代码中,我们使用了文件锁来保证线程安全,每个线程都打开了自己的文件句柄,而且我们使用了线程池来管理多个线程,从而提高了效率。

  •