中央大派遣的简单示例

编程入门 行业动态 更新时间:2024-10-28 08:16:24
本文介绍了中央大派遣的简单示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是Mac的新手编程,对Grand Central Dispatch感到非常惊讶.我读到了这本书,看起来像是并行编程的完美解决方案.我使用POSIX线程,并且想要转到GCD.

I'm newbie programming for mac and i'm really surprised on Grand Central Dispatch. I read about that and looks like the perfect solution for parallel programming. I worked with POSIX threads and want to move to GCD.

我在Apple Developer Connection中看到了示例代码,但是这让我非常困惑.我搜索了一个简单的示例,其中有两个线程可以启动,但是找不到.

I saw the samples codes in the Apple Developer Connection, but It confused me so much. I searched for an easy example with two threads to start but i can't find it.

如何使用GCD执行此示例代码?

How can I do this sample code using GCD ???

#include <stdio.h> /* standard I/O routines */ #include <pthread.h> /* pthread functions and data structures */ /* function to be executed by the new thread */ void* do_loop(void* data) { int i; /* counter, to print numbers */ int j; /* counter, for delay */ int me = *((int*)data); /* thread identifying number */ for (i=0; i<10; i++) { for (j=0; j<500000; j++) /* delay loop */ ; printf("'%d' - Got '%d'\n", me, i); } /* terminate the thread */ pthread_exit(NULL); } void* th2(void* data) { cout << "Thread nº 2" << endl; } int main(int argc, char* argv[]) { int thr_id; /* thread ID for the newly created thread */ pthread_t p_thread1; pthread_t p_thread2; /* thread's structure */ int a = 1; /* thread 1 identifying number */ int b = 2; /* thread 2 identifying number */ /* create a new thread that will execute 'do_loop()' */ thr_id = pthread_create(&p_thread1, NULL, do_loop, (void*)&a); /* run 'do_loop()' in the main thread as well */ thr_id = pthread_create(&p_thread2, NULL, th2, (void*)&b); return 0; }

预先感谢

推荐答案

会是这样的:

// The block replaces your doLoop function, it basically does the same thing dispatch_block_t myBlock = ^{ int i; /* counter, to print numbers */ int j; /* counter, for delay */ dispatch_queue_t me = dispatch_get_current_queue(); /* The queue which currently runs this block */ for (i=0; i<10; i++) { for (j=0; j<500000; j++) /* delay loop */ ; printf("'%s' - Got '%d'\n", dispatch_queue_get_label(me), i); // Print the name of the queue } }; // Create two queues dispatch_queue_t queue1 = dispatch_queue_create("my.totally.unique.and.reverse.dns.identifier.1", NULL); dispatch_queue_t queue2 = dispatch_queue_create("my.totally.unique.and.reverse.dns.identifier.2", NULL); // Let both execute the block dispatch_async(queue1, myBlock); dispatch_async(queue2, myBlock); // And then release the queues because we are great citizens who care about memory dispatch_release(queue1); dispatch_release(queue2);

更多推荐

中央大派遣的简单示例

本文发布于:2023-11-23 08:51:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620823.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:示例   中央   简单

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!